首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >C#将txt文件名添加到组合框

C#将txt文件名添加到组合框
EN

Stack Overflow用户
提问于 2016-12-11 16:54:33
回答 2查看 1.5K关注 0票数 0

如何将某个目录中的txt文件添加到组合框中,但仅添加其名称。比如,有一个名为"Data“的文件夹,里面有3个txt文件,名为”食品饮料“

现在我想把他们的名字添加到一个组合框中。我该怎么做呢?

EN

回答 2

Stack Overflow用户

发布于 2016-12-11 17:00:36

您需要使用此路径中的DirectoryInfo("pathToDirectory")GetFiles("*.txt")。下一个数组FileInfo作为DataSource添加到ComboBox。这是示例。

代码语言:javascript
运行
复制
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";

这段代码经过测试,运行良好。

票数 3
EN

Stack Overflow用户

发布于 2016-12-11 17:01:23

这将为您提供'path‘中的任何文本文件,删除目录和扩展名并添加到combobox:

代码语言:javascript
运行
复制
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);
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/41084457

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档