2013-11-01 88 views
1

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

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?或者是在这里更好的方式来搜索子目录中的第一个文件?

+1

可能重复[?如何使用DirectoryInfo.GetFiles,并将它找到的第一个匹配后停止(http://stackoverflow.com/questions/9120737/how-to-use-directoryinfo-getfiles-and-have-it-stop-after-finding-the-first-match) –

+0

@AlexFilipovici这不是真正的骗局,因为在这里我们正在寻找一个单一的文件在目录中。对'File.Exists'的简单调用就足够了。 –

+0

@DavidHeffernan:_...并深入根据需要... _ –

回答

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; 
} 
+0

啊......太晚了;-) –

+0

不仅仅是我想要的,而是可行的。感谢您的代码。 –

2

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

这实际上反映了它将在Win32中以FindFirstFile完成的方式。当使用FindFirstFile时,您总是需要自己实现子目录递归,因为FindFirstFileSearchOption.AllDirectories没有任何差别。

+0

那么过滤结果数组'findedDirectories'可能会更容易(也可能更慢)? –