使用递归的方式遍历指定路径下的所有文件。
我封装了一个类:
using System.Collections.Generic;
using System.IO;
namespace ForeachFile
{
/// <summary>
/// 文件收集器。遍历指定路径下的所有文件
/// </summary>
class FileGather
{
#region 单例
private static FileGather singleton = null;
private FileGather() { }
public static FileGather Singleton()
{
if (singleton == null) singleton = new FileGather();
return singleton;
}
#endregion
#region 属性
public string Path { get; set; } = "";
public List<string> FileList { get; set; } = new List<string>();
/// <summary>忽略的文件夹名</summary>
public List<string> IgnoreFolder { get; set; } = new List<string>();
/// <summary>忽略文件类型</summary>
public List<string> IgnoreFileType { get; set; } = new List<string>();
#endregion
#region 公开方法
public void StartGather()
{
ReadPath(Path);
}
#endregion
#region 内部方法
private void ReadPath(string folderPath)
{
DirectoryInfo currentFolder = new DirectoryInfo(folderPath);
// 读取文件夹
foreach (DirectoryInfo folder in currentFolder.GetDirectories())
{
if (IgnoreFolder.Contains(folder.Name)) continue;
ReadPath(folder.FullName);
}
// 读取文件
foreach (FileInfo file in currentFolder.GetFiles())
{
if (IgnoreFileType.Contains(file.Extension)) continue;
FileList.Add(file.FullName);
}
}
#endregion
}
}
如何使用:
using System;
namespace ForeachFile
{
class Program
{
static void Main()
{
// 设置路径
FileGather.Singleton().Path = "D:\\";
// 忽略“回收站”与“卷标信息”文件夹
FileGather.Singleton().IgnoreFolder.Add("$RECYCLE.BIN");
FileGather.Singleton().IgnoreFolder.Add("System Volume Information");
// 忽略压缩文件
FileGather.Singleton().IgnoreFileType.Add(".zip");
FileGather.Singleton().IgnoreFileType.Add(".rar");
FileGather.Singleton().IgnoreFileType.Add(".7z");
// 开始收集
FileGather.Singleton().StartGather();
Console.WriteLine("收集完成。文件数:" + FileGather.Singleton().FileList.Count);
// 打印文件列表
foreach (var file in FileGather.Singleton().FileList)
{
Console.WriteLine(file);
}
Console.ReadKey();
}
}
}
网友评论