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?
Answered by:- vikas_jk
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".
Answered by:- bhanu
We can also try this, to get all files in directory and sub-directory
string[] getAllFiles= Directory.GetFiles("pathToDir/Dir", "*.*", SearchOption.AllDirectories)
foreach (var file in allfiles){
FileInfo info = new FileInfo(file);
}
In the above code, "*.*" is search pattern, which means to select all files, whether it is text file or image or xml file or any other file.
Answered by:- pika
Here is the console application sample to get all files in directory in C#
using System.IO; //required namespace
DirectoryInfo d = new DirectoryInfo(@"D:\FolderToSearch"); //Assuming Test is your Folder
FileInfo[] Files = d.GetFiles("*.txt"); //Getting Text files only using it's extension '.txt'
string str = "";
foreach(FileInfo file in Files )
{
str = str + ", " + file.Name;
}
Console.WriteLine("All Files names are": +str);
This is just sample application code, without adding "class maiin" etc.
Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly