How to get all files inside folder using C# easily?


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?


Asked by:- bhanu
1
: 4660 At:- 2/22/2021 8:56:20 PM
C# get files from folder







3 Answers
profileImage 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".

1
At:- 2/23/2021 3:21:54 PM
Ok got it, thanks for help. I was able to execute it. 0
By : bhanu - at :- 2/23/2021 5:16:08 PM


profileImage 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.

1
At:- 4/21/2021 11:29:47 AM
I think this easier code to get all files in directory 0
By : pika - at :- 6/3/2022 7:41:06 AM


profileImage 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.

0
At:- 6/3/2022 7:43:21 AM






Login/Register to answer
Or
Register directly by posting answer/details

Full Name *

Email *




By posting your answer you agree on privacy policy & terms of use