软件编程
位置:首页>> 软件编程>> C#编程>> c# 遍历获取所有文件的示例代码

c# 遍历获取所有文件的示例代码

作者:Bruce-  发布时间:2022-11-21 20:01:43 

标签:c#,遍历,文件

在使用C#进行桌面应用开发中,经常会有对文件进行操作的情况,这时可能会需要对文件夹进行文件扫描,获取所有文件

做法如下


/// <summary>
   /// 遍历获取所有文件
   /// </summary>
   /// <param name="filePathByForeach"></param>
   /// <param name="result"></param>
   public static void ForeachFile(string filePathByForeach, ref string result)
   {
     try
     {
       DirectoryInfo theFolder = new DirectoryInfo(filePathByForeach);
       DirectoryInfo[] dirInfo = theFolder.GetDirectories();//获取所在目录的文件夹
       FileInfo[] file = theFolder.GetFiles();//获取所在目录的文件

foreach (FileInfo fileItem in file) //遍历文件
       {
         result += fileItem.DirectoryName + @"\" + fileItem.Name + "\n";
       }
       //遍历文件夹
       foreach (DirectoryInfo NextFolder in dirInfo)
       {
         ForeachFile(NextFolder.FullName, ref result);
       }

}
     catch (Exception)
     {
       throw;
     }

}

来源:https://www.cnblogs.com/xwcs/p/13508569.html

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com