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

This blog post will explain in simple steps how to the list of files within a directory using 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 retrieves all the file names with the complete path in the directory.

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

The below will retrieve all the files names along with their 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 do not search the subdirectories, to include the subdirectories, we can pass the third parameter of type enum “search option. directories“.

    1 Comment

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

C# Compiler Error CS0442 – ‘Property’: abstract properties cannot have private accessors Reason for the Error You’ll get this error...
This is a really simple one . Below is a simple example of an enum called “Designation” defined with the...
This blog post explain the usage of the Checked Block in .NET and how you can use them in Visual...