To get the names of a file without the extension included you can use the nifty GetFileNameWithoutExtension()
method of the Path
class.
If you want your DataSource to display the name without the extension, but keep the "value" as a FileInfo
, you can use a little Linq to turn your FileInfo[]
into a Dictionary<string, FileInfo>
, then set the display and value member properties appropriately:
comboBox1.DataSource = new BindingSource(
Files.ToDictionary(x => Path.GetFileNameWithoutExtension(x.Name),
x => x),
null);
comboBox1.DisplayMember = "Key";
comboBox1.ValueMember = "Value";
Remember that a Dictionary
cannot have duplicate keys. In your code you grab all the textfiles of a single directory, so even when we strip the extension off we can be certain that there won't be duplicates. If you change your query in a way that would introduce duplicates into the Dictionary, my answer will throw an exception.
If all you need is the display and value to be the filename without extension its even easier:
comboBox1.DataSource = Files
.Select(x => Path.GetFileNameWithoutExtension(x.Name))
.ToArray();