Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I fill my combobox with .txt files, but only their name without the path?

Tags:

c#

file

combobox

string path = AppDomain.CurrentDomain.BaseDirectory;
string[] filePaths = Directory.GetFiles(path, "*.txt");
foreach (string file in filePaths)
{
    cboLanden.Items.Add(file);
}

This is my code and it returns the full path, I would like to have only the name, without the path in my combobox.

like image 728
Maxim Avatar asked Feb 14 '23 04:02

Maxim


1 Answers

Use Path.GetFileName() to get file name without path:

string path = AppDomain.CurrentDomain.BaseDirectory; 
string[] filePaths = Directory.GetFiles(path, "*.txt"); 
foreach (string file in filePaths) 
{ 
   cboLanden.Items.Add(Path.GetFileName(file)); 
}

Also consider to use files as data source of your comboBox:

 cboLanden.DataSource = Directory.EnumerateFiles(path, "*.txt")
                                 .Select(Path.GetFileName)
                                 .ToList();
like image 178
Sergey Berezovskiy Avatar answered Apr 25 '23 19:04

Sergey Berezovskiy