C#搜索指定文件工具类
/// <summary>
/// 获取路径下所有文件以及子文件夹中文件
/// </summary>
/// <param name="path">全路径根目录</param>
/// <param name="FileList">存放所有文件的全路径</param>
/// <param name="RelativePath"></param>
/// <returns></returns>
public static void GetFile(string path, string fileName, ref string smallDir)
{
DirectoryInfo dir = new DirectoryInfo(path);
FileInfo[] fil = dir.GetFiles();
DirectoryInfo[] dii = dir.GetDirectories();
foreach (FileInfo f in fil)
{
string name = Path.GetFileName(f.FullName.ToString());
//Console.WriteLine(name);
if (name.Contains(fileName)) {
Console.WriteLine(Path.GetDirectoryName(f.FullName));
string[] temp = Path.GetDirectoryName(f.FullName).Split('\\');
smallDir = temp[temp.Length - 1];
return;
}
}
//获取子文件夹内的文件列表,递归遍历
foreach (DirectoryInfo d in dii)
{
if (smallDir == "")
GetFile(d.FullName, fileName, ref smallDir);
}
}
使用
static void Main(string[] args)
{
//文件位置
string smallDir = "";
GetFile("D://C#/", "a.txt", ref smallDir);
Console.write("文件在" + smallDir);
}