1

我有一种情况,我必须找到my.exestartingdirectory&开始命名的第一个文件的路径,\mydir\并根据需要深入。
实际上,IO.Directory.GetFiles它是合适的,但我需要它在找到第一个文件后停止搜索,就像FindFirstFile从 WinAPI 中可能一样。

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);

是否可以在找到第一个文件后以函数的结果为 astring或 anempty string而不是 a的方式停止搜索string array?或者这里有更好的方法来搜索子目录中的第一个文件?

4

2 回答 2

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;
}
于 2013-11-01T15:07:24.870 回答
2

Directory.GetDirectories我想最简单的方法是通过递归调用来将递归组织到子目录中SearchOption.TopDirectoryOnly。在每个目录中使用 . 检查文件是否存在File.Exists

这实际上反映了在 Win32 中使用FindFirstFile. 使用FindFirstFile时总是需要自己实现子目录递归,因为FindFirstFileSearchOption.AllDirectories.

于 2013-11-01T14:15:23.087 回答