If you find this article useful, consider making a small donation to show your support for this web site and its content.
DiscountASP
AboutMe
About me:
Hi. My name is Farooq Kaiser and I'm a software developer from Toronto, Canada.

How to read files in folder and subfolders in C#

by Farooq Kaiser 23. January 2009 03:53
I would like to show you recursively reading files in folder and subfolders in C#.
Since i build this project for web, so please feel free to change for windows or console App. 
   
 protected void Page_Load(object sender, EventArgs e)
    {
        StringBuilder sb = new StringBuilder();
        ReadFolder(new DirectoryInfo(@"C:\Your Path"), ref sb);
        pnlResult.Controls.Add(new LiteralControl(sb.ToString()));
    }

    private void ReadFolder(DirectoryInfo directoryInfo, ref StringBuilder sb)
    {
        // Reads files 
foreach (FileInfo file in directoryInfo.GetFiles())
        {
            sb.AppendFormat("File:{0}<br>",file.FullName);   
        }
 
        // Reads Folders
        foreach (DirectoryInfo subfolder in directoryInfo.GetDirectories())
        {
            sb.AppendFormat("Folder:{0}<br>",subfolder.FullName); 
            ReadFolder(subfolder, ref sb);
        }
    }

Currently rated 2.0 by 1 people

  • Currently 2/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: , ,

.NET | C#

Jobs Autos Real estate Videos Power by Google
awesome comments