我根据这个文件名有文件名。我需要找到文件的路径。 如何根据文件名查找文件的路径?我需要根据文件名示例代码找到文件的路径:
string path= System.IO.Directory.GetDirectories(@"c:\", "kategori",System.IO.SearchOption.AllDirectories).First();
但我需要:
string path= System.IO.Directory.GetDirectories(@"anyFolder", "kategori",System.IO.SearchOption.AllDirectories).First();
Main()
{
string path = PathFinder("Afilename")
}
output: C:\myFiles\AfileName
string PathFinder(string fileName)
{
..................
.................
........
.......
....
..
.
}
答案 0 :(得分:3)
这样的功能可能适合你:
public static String SearchFileRecursive(String baseFolderPath, String fileName)
{
// Returns, if found, the full path of the file; otherwise returns null.
var response = Path.Combine(baseFolderPath, fileName);
if (File.Exists(response))
{
return response;
}
// Recursion.
var directories = Directory.GetDirectories(baseFolderPath);
for (var i = 0; i < directories.Length; i++)
{
response = SearchFileRecursive(directories[i], fileName);
if (response != null) return response;
}
// { file was not found }
return null;
}
答案 1 :(得分:2)
答案 2 :(得分:2)
我想要更多LINQish方式:
public static IEnumerable<FileInfo> FindFile(string fileName)
{
if (String.IsNullOrEmpty(fileName))
throw new ArgumentException("fileName");
return Directory.GetLogicalDrives()
.SelectMany(drive => FindFile(fileName, drive));
}
public static IEnumerable<FileInfo> FindFile(string fileName, string folderName)
{
if (String.IsNullOrEmpty(fileName))
throw new ArgumentException("fileName");
if (String.IsNullOrEmpty(fileName))
throw new ArgumentException("folderName");
var matchingFiles = Directory.EnumerateFiles(folderName)
.Where(file => Path.GetFileName(file) == fileName)
.Select(file => new FileInfo(file));
var matchingFilesFromSubDirs = Directory.EnumerateDirectories(folderName)
.SelectMany(directory => FindFile(fileName, directory));
return matchingFiles.Concat(matchingFilesFromSubDirs);
}
可以用于:
foreach (var file in FindFile("myFile.ext"))
{
Console.WriteLine("Name: " + file.FullName);
}