Open In App

C# Program to Get the List of Files From Given Directory

Last Updated : 01 Feb, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Given a directory, now we will find the list of files from the given directory. So for this, we use the GetFiles() method of the Directory class. This method is used to find the list of files from the given directory or sub directories. The overloaded methods of this method are:

1. GetFiles(String): This method will return the names of files (including their paths) in the specified directory.

Syntax:

public static string[] GetFiles (string path);

2. GetFiles(String, String): This method will return the names of files (including their paths) that match the specified search pattern in the specified directory.

Syntax:

public static string[] GetFiles (string path, string searchPattern);

3. GetFiles(String, String, SearchOption): This method will return the names of files (including their paths) that match the specified search pattern and enumeration options in the specified directory.

Syntax:

public static string[] GetFiles (string path, string searchPattern, System.IO.EnumerationOptions enumerationOptions);

4. GetFiles(String, String, SearchOption): This method will return the names of files (including their paths) that match the specified search pattern in the specified directory, using a value to determine whether to search subdirectories.

Syntax:

public static string[] GetFiles (string path, string searchPattern, System.IO.SearchOption searchOption);

Example: In this example, we are going to find the files present in the C drive using the GetFiles() method. 

C#




// C# program to get the list of 
// files from the specified directory
using System;
using System.IO;
  
class GFG{
  
static void Main()
{
      
    // Getting files from C drive
    // Using the GetFiles() method
    string[] filedata = Directory.GetFiles(@"C:\");
      
    // Displaying the file name one by one
    foreach (string i in filedata)
    {
        Console.WriteLine(i);
    }
}
}


Output:

A
Dell
flask web application

Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads