get files in folder c# code example
Example 1: c# get files of type in directory
string[] files = System.IO.Directory.EnumerateFiles(directory, "*.*").ToArray();
Example 2: c# retrieve files in folder
using System.IO;
string[] filePaths = Directory.GetFiles(@"c:\MyDir\");
// returns:
// "c:\MyDir\my-car.BMP"
Example 3: 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 4: C# get all files in directory
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>();
}
}));
}