C# Get File List From Directory
Directory.GetFiles in System.IO namespace returns a string array contains the full paths of all the files contained inside the specified directory. This method can be used.
Sample directory and file structure is like below:
“C:\TestDirectory\Files\file1.png”
“C:\TestDirectory\Files\file2.avi”
“C:\TestDirectory\Files\file3.jpg”
“C:\TestDirectory\Files\SubFolder\file4.jpg”
“C:\TestDirectory\Files\SubFolder\file5.avi”
This example writes the name of files from a directory.
string[] filePaths = Directory.GetFiles(@"C:\TestDirectory\Files\"); foreach (string file in filePaths) Console.WriteLine(file); // Result: // "C:\TestDirectory\Files\file1.png" // "C:\TestDirectory\Files\file2.avi" // "C:\TestDirectory\Files\file3.jpg"
Also you can add search pattern. Second parametre is search string to match against the names of files in path. The parameter cannot end in two periods (“..”) or contain two periods (“..”) followed by System.IO.Path.DirectorySeparatorChar or System.IO.Path.AltDirectorySeparatorChar, nor can it contain any of the characters in System.IO.Path.InvalidPathChars.
string[] filePaths = Directory.GetFiles(@"C:\TestDirectory\Files\", "*.avi"); foreach (string file in filePaths) Console.WriteLine(file); // Result: // "C:\TestDirectory\Files\file2.avi"
“Directory.GetFiles” method includes only the current directory in a search as default. If you want to search all subdirectories, you can set the search option as third parameter(SearchOption.AllDirectories).
string[] filePaths = Directory.GetFiles(@"C:\TestDirectory\Files\", "*.avi", SearchOption.AllDirectories); foreach (string file in filePaths) Console.WriteLine(file); // Result: // "C:\TestDirectory\Files\file2.avi" // "C:\TestDirectory\Files\SubFolder\file5.avi"
For .NET Framework 4.0 and layer, you can use this example.
//For .NET 4.0 and later, var filePaths = Directory.EnumerateFiles(@"C:\TestDirectory\Files\").Where(s => s.EndsWith(".avi")); foreach (string file in filePaths) Console.WriteLine(file); // Result: // "C:\TestDirectory\Files\file2.avi"