如何将某个目录中的txt文件添加到组合框中,但仅添加其名称。比如,有一个名为"Data“的文件夹,里面有3个txt文件,名为”食品饮料“
现在我想把他们的名字添加到一个组合框中。我该怎么做呢?
发布于 2016-12-11 17:00:36
您需要使用此路径中的DirectoryInfo("pathToDirectory")和GetFiles("*.txt")。下一个数组FileInfo作为DataSource添加到ComboBox。这是示例。
DirectoryInfo d = new DirectoryInfo(@"C:\Users\Mateusz\Desktop\test");//Assuming Test is your Folder
FileInfo[] Files = d.GetFiles("*.txt"); //Getting Text files
comboBox1.DataSource = Files;
comboBox1.DisplayMember = "Name";这段代码经过测试,运行良好。

发布于 2016-12-11 17:01:23
这将为您提供'path‘中的任何文本文件,删除目录和扩展名并添加到combobox:
string[] textFiles = System.IO.Directory.GetFiles(path, "*.txt");
foreach (string file in textFiles)
{
// Remove the directory from the string
string filename = file.Substring(file.LastIndexOf(@"\") + 1);
// Remove the extension from the filename
string name = filename.Substring(0, filename.LastIndexOf(@"."));
// Add the name to the combo box
combobox1.Items.Add(name);
}https://stackoverflow.com/questions/41084457
复制相似问题