How to retreive the list of files from Directory in C# ?

Here’s a simple example that gets all the file names from a given directory .

The Directory class defined in the System.IO namespace provides the static GetFiles method that retreives all the file names with the complete path in the directory .

The below will retreive all the files names along with its complete path from C:\temp

private void Form1_Load(object sender, EventArgs e)
{
     string[] lstFiles = Directory.GetFiles(@"c:\temp");
     foreach (string file in lstFiles)
     {
          listBox1.Items.Add(file);
     }
}

It is also possible to filter and select only the files with a
particular extension .

For example , if i want to search for all exe files with in the folder
, i can use the filter as stated below .

private void Form1_Load(object sender, EventArgs e)
{
     string[] lstFiles = Directory.GetFiles(@"c:\temp","*.exe");
     foreach (string file in lstFiles)
     {
          listBox1.Items.Add(file);
     }
}

The above examples doesnot search the sub directories , to include the sub directories , we can pass the third parameter of type enum “SearchOption.AllDirectories” .

If you enjoyed this post, please consider leaving a comment or subscribing to the RSS feed to have future articles delivered to your feed reader.

No Responses

  1. How to retreive the list of files from Directory in C# | ProgramInDotnet August 8, 2011 Reply

Leave a Reply


x

Interesting BlogPosts to read

How to get an Enumerator from range of elements from ArrayList in C# ?
The code snippet shown in this blog post demonstrates how you can get the enumeraor from a range of ...
How to check for the column name in an SqlDataReader Object in C# ?
When working in ADO.NET for data access , there are times when you want to check to see if a column ...
How to convert Array to List in C#?
Want to convert array of strings to List of strings in C# ? . Below is a sample code to illustrate t...