C# 如何在列表框中列出选定目录中的文本文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1277222/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to list text files in the selected directory in a listbox?
提问by Lady Sour
How can I list the text files in a certain directory (C:\Users\Ece\Documents\Testings) in a listbox of a WinForm(Windows application)?
如何在 WinForm(Windows 应用程序)的列表框中列出某个目录(C:\Users\Ece\Documents\Testings)中的文本文件?
采纳答案by jay_t55
// What directory are the files in?...
// 文件在哪个目录?...
DirectoryInfo dinfo = new DirectoryInfo(@"C:\TestDirectory");
// What type of file do we want?...
// 我们想要什么类型的文件?...
FileInfo[] Files = dinfo.GetFiles("*.txt");
// Iterate through each file, displaying only the name inside the listbox...
// 遍历每个文件,只显示列表框内的名称...
foreach( FileInfo file in Files )
{
listbox1.Items.Add(file.Name);
}
// A statement, followed by a smiley face... That oughta do it. ;o)
// 一个声明,然后是一个笑脸......应该这样做。;o)
回答by Lloyd Powell
To get the txt files, try this:
要获取 txt 文件,请尝试以下操作:
var folder = @"C:\Users\Ece\Documents\Testings";
var txtFiles = Directory.GetFiles(folder, "*.txt");
listBox.Items.AddRange(txtFiles);