How to list text files in the selected directory i

2019-01-27 14:29发布

问题:

How can I list the text files in a certain directory (C:\Users\Ece\Documents\Testings) in a listbox of a WinForm(Windows application)?

回答1:

// 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)



回答2:

To get the txt files, try this:

string folder = @"C:\Users\Ece\Documents\Testings";
string[] txtfiles = Directory.GetFiles(folder, "*.txt");

listBox.Items.AddRange(txtFiles);