C# 返回文件夹及子目录

     /// <summary>
     /// 返回文件夹及子目录的文件夹
     /// </summary>
     /// <param name="directory"></param>
     /// <param name="files"></param>
     public static void GetFiles(string directory, ref Dictionary<string, FileInfo> files)
     {
         DirectoryInfo di = new DirectoryInfo(directory);
         if (di.Exists)
         {
             foreach (FileInfo f in di.GetFiles())
             {
                 if (files.ContainsKey(f.FullName)) continue;
                 files.Add(f.FullName, f);
             }

             foreach (DirectoryInfo d in di.GetDirectories())
             {
                 GetFiles(d.FullName, ref files);
             }
         }
     }

     /// <summary>
     /// 返回指定类型的文
     /// </summary>
     /// <param name="directory"></param>
     /// <param name="extension"></param>
     /// <param name="files"></param>
     public static void GetFiles(string directory, string extension, ref Dictionary<string, FileInfo> files)
     {
         DirectoryInfo di = new DirectoryInfo(directory);
         if (di.Exists)
         {
             foreach (FileInfo f in di.GetFiles($"*{extension}"))
             {
                 if (files.ContainsKey(f.FullName)) continue;
                 files.Add(f.FullName, f);
             }

             foreach (DirectoryInfo d in di.GetDirectories())
             {
                 GetFiles(d.FullName, extension, ref files);
             }
         }
     }
//调用方式        
Dictionary<string,FileInfo> files = new Dictionary<string,FileInfo>(); GetFiles(AppContext.BaseDirectory,".jpg", ref files);

 

posted @ 2024-07-15 09:54  猫狼  阅读(8)  评论(0编辑  收藏  举报