c#遞歸遍歷文件夾示例。本站提示廣大學習愛好者:(c#遞歸遍歷文件夾示例)文章只能為提供參考,不一定能成為您想要的結果。以下是c#遞歸遍歷文件夾示例正文
代碼很簡略,指定須要遞歸遍歷的文件夾和遍歷規矩就要可以運轉了
/// <summary>
/// 遞歸獲得文件夾目次下文件
/// </summary>
/// <param name="pathName">須要遞歸遍歷的文件夾</param>
/// <param name="fileRule">遍歷規矩『拜托』</param>
public static void LoopFolder(string pathName, Action<FileInfo> fileRule)
{
if (string.IsNullOrEmpty(pathName))
throw new ArgumentNullException(pathName);
Queue<string> _pathQueue = new Queue<string>();
_pathQueue.Enqueue(pathName);
while (_pathQueue.Count > 0)
{
string _path = _pathQueue.Dequeue();
DirectorySecurity _pathSecurity = new DirectorySecurity(_path, AccessControlSections.Access);
if (!_pathSecurity.AreAccessRulesProtected)//文件夾權限能否可拜訪
{
DirectoryInfo _directoryInfo = new DirectoryInfo(_path);
foreach (DirectoryInfo diChild in _directoryInfo.GetDirectories())
{
_pathQueue.Enqueue(diChild.FullName);
}
foreach (FileInfo file in _directoryInfo.GetFiles())
{
fileRule(file);
}
}
}
}
舉例應用
CSharpToolV2.LoopFolder(@"C:\Users\Administrator\Downloads\", (FileInfo file) =>
{
if (file.Extension.Equals(".xls"))//獲得excel類型文件
{
Console.WriteLine(string.Format("============{0}==============", file.FullName));
}