views:

700

answers:

2

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  A: 

To get the txt files, try this:

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

listBox.Items.AddRange(txtFiles);
ThePower
ok to where do I write this? the program does compile but the listbox doesnt show anything
Lady Sour
Whenever you want to get the code (maybe on a Button_Click event? for a Get Files button?
ThePower
If you are going to use a button, or a method that will be allowed to be clicked multiple times you must clear the list before filling it again.
ThePower
Is there any way to list only the file names and dates ?
Lady Sour
you can ditch the need for the loop by using the listbox's AddRange method with txtfiles
CodeByMoonlight
Good shout, thanks :-)
ThePower
+1  A: 

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

baeltazor