Get Files from Directory in C#

 

In C#, we can easily read the files from particular directory by using Directory.GetFiles() method. Directory class is available in System.IO namespace. We can read the files from particular directory as shown below. 

using System; 

using System.IO;

 

namespace CSharpDirectoryFiles 

{ 

    class Program 

    { 

        static void Main(string[] args) 

        { 

            string dirToRead ="E:\\Files" ; 

            string pattern = "*";

 

            string[] fPaths =  Directory.GetFiles(dirToRead, pattern); 

            foreach (string fPath in fPaths) 

            { 

                FileInfo fInfo = new FileInfo(fPath); 

                Console.WriteLine("Path = {0} Filename: {1} ext: {2} " + "touch: {3} size: {4}",fPath, fInfo.Name, fInfo.Extension,fInfo.LastWriteTime, fInfo.Length);                

            } 

            Console.ReadLine(); 

        } 

    } 

}

 

As shown above we are getting all files from Files directory in E drive. If you want to get only specific files change pattern. For example if we want to get only excel file change pattern to “*.xlsx”. 

When we execute the above code the output displays as shown below. 

                                                                                                                                             

                                                                                                             CSharpDirectoryFiles.zip (23.25 kb)