C# iterate folder and find files recursively in the specified folder

Lionsure 2020-08-03 Original by the website

When you want to list all the folders and files in a folder, or find a specific file, you must iterate the folder. The folders are all level by level, recursion just meets this rule, the following C# code will use the recursive method to achieve.

Use C# to iterate the folder and list all the subfolders and files in the folder. The method is the same as finding the specified file in the folder, but the purpose is different. For ease of use, two implementation methods will be listed.

 

1. C# iterate folder recursively and list all subfolders and files

/// <summary>
       /// C# iterate folder recursively
       /// </summary>
       /// <param name="path">Folder path</param>

       private void ForeachForldersAndFiles(string path)
       {
              DirectoryInfo di = new DirectoryInfo(path);
              DirectoryInfo[] arrDir = di.GetDirectories();

       foreach (DirectoryInfo dir in arrDir)
              {
                     Response.Write("<br />" + dir.Name + ": <br />");
                     ForeachForldersAndFiles(di + dir.ToString() + "\\");
              }

       foreach (FileInfo fi in di.GetFiles("*.*"))
              {
                     Response.Write(fi.Name + "<br />");
              }
       }

Call: ForeachForldersAndFiles(@"G:\xq\");

After testing, it can accurately list all subfolders and files in any folder, but you must ensure that the code has access permissions to the specified folder.

 

2. C# find files recursively in the specified folder

/// <summary>
       /// C# find files recursively
       /// </summary>
       /// <param name="filePath">Folder path</param>
       /// <param name="fileName">Find file name</param>
       /// <returns>Return true if found, otherwise return false</returns>

       private bool FindFile(string filePath, string fileName)
       {
              if (string.IsNullOrEmpty(fileName)) return false;

       DirectoryInfo di = new DirectoryInfo(filePath);
              DirectoryInfo[] arrDir = di.GetDirectories();

       foreach (DirectoryInfo dir in arrDir)
              {
                      if (FindFile(di + dir.ToString() + "\\", fileName))
                             return true;
              }

       foreach (FileInfo fi in di.GetFiles("*.*"))
              {
                     if (fi.Name == fileName)
                            return true;
                     }
                     return false;
       }

Call: FindFile(@"G:\xq\", "test.txt");

The code has also passed the test and can be used directly. As long as the path is correct, the file specified by the file name exists, and the specified file can be accessed, it can be found.