I have been reading this article to read file in C#, but how can I read all files inside folders, so basically how to get all files from directory or folder using C# and then read them?
You can simply use the "DirectoryInfo" class, and the ".GetFiles" method, as shown in below code
DirectoryInfo dir = new DirectoryInfo(@"E:\YourFolderName");
FileInfo[] AllTxtFiles= dir.GetFiles("*.txt"); //Getting only Text files
foreach(var fle in AllTextFiles)
{
//read files content or do something
}
OR
You can simply use
foreach (string file in Directory.EnumerateFiles(folderPath, "*.txt"))
{
//read content
string contents = File.ReadAllText(file);
}
For both of the above solutions, you will have to use namespace "System.IO".
Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly