文件夹遍历递归与非递归算法(C#实现)

1.递归算法

using System;

using System.IO;

using System.Collections.Generic;

//暂存递归时文件夹绝对路径,防止异常时丢失

private string strTemp="";

//存储该文件内所有文件绝对路径泛型List

private List<string> AllFiles=new List<string>();

public void GetAllFiles(string strFolderPath)

{

     GetCurrentFiles(strFolderPath);

     GetChildFiles(strFolderPath);

}

//获取该文件夹的直接文件

private void GetCurrentFiles(string strFolderPath)

{

   foreach(string temp in Directory.GetFiles(strFolderPath))

  {

      try

      {

           AllFiles.Add(temp);

      }

      catch

      {

          continue;

      }

  }

}

//递归获取所有子文件夹中的文件

private void GetChildFiles(string strFolderPath)

{

      foreach(string temp in Directory.GetDirectories(strFolderPath))

      {

             this.strTemp=temp;

             GetCurrentFiles(strTemp);

             GetChildFiles(strTemp);

      }

}

2.非递归算法

using System;

using System.IO;

using System.Collections.Generic;

 

public List<string> GetAllFiles(string strFolderPath)

{

      List<string> AllFiles=new List<string>();

      Queue<string> AllFolders=new Queue<string>();

      AllFolders.EnQueue(strFolderPath);

      while(AllFolders.Count>0)

      {

             string temp=AllFolders.DeQueue();

             foreach(string temp1 in Directory.GetDirectories(strFolderPath))

             {

                  AllFolder.EnQueue(temp);

             }

              foreach(string temp2 in Directory.GetFiles(strFolderPath))

             {

                 try

                {

                      AllFiles.Add(temp);

                 }

                 catch

                 {

                      continue;

                  }

            }

      }

       return AllFiles;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值