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
: 190 At:- 2/22/2021 8:56:20 PM
C# get files from folder

1 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


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

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

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

Full Name *

Email *

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