我有一种情况,我必须找到从my.exe
开始的名为startingdirectory
的第一个文件的路径。 \mydir\
并根据需要深入了解
实际上,IO.Directory.GetFiles
是合适的,但我需要它在找到第一个文件之后停止搜索,就像WinAPI中的FindFirstFile
一样。
VB.NET
Dim findedDirectories() As String = IO.Directory.GetFiles( _
startingdirectory & "\mydir\", "my.exe", IO.SearchOption.AllDirectories)
C#
string[] findedDirectories = IO.Directory.GetFiles( _
startingdirectory + "\\mydir\\", "my.exe", IO.SearchOption.AllDirectories);
是否可以在找到第一个文件之后停止搜索,其方式是函数的结果为string
或empty string
,而不是string array
?或者在这里搜索子目录中的第一个文件是更好的方法吗?
答案 0 :(得分:4)
以下解决方案可以提供帮助:
/// <summary>
/// Searches for the first file matching to searchPattern in the sepcified path.
/// </summary>
/// <param name="path">The path from where to start the search.</param>
/// <param name="searchPattern">The pattern for which files to search for.</param>
/// <returns>Either the complete path including filename of the first file found
/// or string.Empty if no matching file could be found.</returns>
public static string FindFirstFile(string path, string searchPattern)
{
string[] files;
try
{
// Exception could occur due to insufficient permission.
files = Directory.GetFiles(path, searchPattern, SearchOption.TopDirectoryOnly);
}
catch (Exception)
{
return string.Empty;
}
// If matching files have been found, return the first one.
if (files.Length > 0)
{
return files[0];
}
else
{
// Otherwise find all directories.
string[] directories;
try
{
// Exception could occur due to insufficient permission.
directories = Directory.GetDirectories(path);
}
catch (Exception)
{
return string.Empty;
}
// Iterate through each directory and call the method recursivly.
foreach (string directory in directories)
{
string file = FindFirstFile(directory, searchPattern);
// If we found a file, return it (and break the recursion).
if (file != string.Empty)
{
return file;
}
}
}
// If no file was found (neither in this directory nor in the child directories)
// simply return string.Empty.
return string.Empty;
}
答案 1 :(得分:2)
我想最简单的方法是通过递归调用[{1}}传递Directory.GetDirectories
来自行组织递归到子目录。在每个目录中使用SearchOption.TopDirectoryOnly
检查文件是否存在。
这实际上反映了使用File.Exists
在Win32中完成的方式。使用FindFirstFile
时,您始终需要自己实现子目录递归,因为FindFirstFile
与FindFirstFile
没有任何关系。