使用IO.Directory.GetFiles的FindFirstFile

时间:2013-11-01 14:11:36

标签: c# vb.net

我有一种情况,我必须找到从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);

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

2 个答案:

答案 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时,您始终需要自己实现子目录递归,因为FindFirstFileFindFirstFile没有任何关系。