c# list all files in directory code example
Example 1: c# list all files in a directory and subdirectory
string[] allfiles = Directory.GetFiles("path/to/dir", "*.*", SearchOption.AllDirectories);
Example 2: read folder c#
string mydocpath=Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
StringBuilder sb = new StringBuilder();
foreach (string txtName in Directory.GetFiles(@"D:\Links","*.txt"))
{
using (StreamReader sr = new StreamReader(txtName))
{
sb.AppendLine(txtName.ToString());
sb.AppendLine("= = = = = =");
sb.Append(sr.ReadToEnd());
sb.AppendLine();
sb.AppendLine();
}
}
using (StreamWriter outfile=new StreamWriter(mydocpath + @"\AllTxtFiles.txt"))
{
outfile.Write(sb.ToString());
}
Example 3: c# retrieve files in folder
string[] filePaths = Directory.GetFiles(@"c:\MyDir\", "*.bmp");
// returns:
// "c:\MyDir\my-car.BMP"
Example 4: C# get all files in directory
//path is the path of the directory to get files from
//searchPattern is to get specific files. If you want only exe files you enter *.exe
private static IEnumerable<string> GetAllFiles(string path, string searchPattern)
{
return Directory.EnumerateFiles(path, searchPattern).Union(
Directory.EnumerateDirectories(path).SelectMany(d =>
{
try
{
return GetAllFiles(d, searchPattern);
} catch(Exception e)
{
return Enumerable.Empty<string>();
}
}));
}
Example 5: list all files in directory and subdirectories c#
string[] entries = Directory.GetFileSystemEntries(path, "*", SearchOption.AllDirectories);