-1

I need hide ".txt" extensions in "combobox" and i dont know how.

.txt

And how i can do that, that files will loaded from actualy addresesr and some folder? Now i using this code:

Im using this code now:

DirectoryInfo di = new DirectoryInfo(@"C:\Users\JD_1609\source\repos\WindowsFormsApp1\WindowsFormsApp1\bin\Debug\PCs");
FileInfo[] Files = di.GetFiles("*.txt");

comboBox1.DataSource = Files;
comboBox1.DisplayMember = "Name";

But if i transfer it to other pc so its will not working right? So how i can load files from actually addresser?

maccettura
  • 10,514
  • 3
  • 28
  • 35
JD_1609
  • 37
  • 7
  • How are you displaying the files in your combobox? Instead of displaying the files with the extension, you should display just the names – maccettura Apr 25 '18 at 21:24
  • So... show how you assign it to the combobox... – Ron Beyer Apr 25 '18 at 21:24
  • Im using this code now: DirectoryInfo di = new DirectoryInfo(@"C:\Users\JD_1609\source\repos\WindowsFormsApp1\WindowsFormsApp1\bin\Debug\PCs"); FileInfo[] Files = di.GetFiles("*.txt"); comboBox1.DataSource = Files; comboBox1.DisplayMember = "Name"; – JD_1609 Apr 25 '18 at 21:32
  • Do you want your Value to be the full path? Just the name with extension? – maccettura Apr 25 '18 at 21:44
  • I need only write file name to combobox without extension. – JD_1609 Apr 25 '18 at 21:45

1 Answers1

0

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();
maccettura
  • 10,514
  • 3
  • 28
  • 35