C# 指定路径 搜索文件
2018-07-31 本文已影响0人
ZoneWonderful
实现
/// <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);
}
//return smallDir;
}
调用
string path = "路径";
string smallDir = "";
string fileName = "你想要搜索的文件名";
GetFile(path, fileName,ref smallDir);
MessageBox.Show(smallDir);