2013-11-01 93 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'可能會更容易(也可能更慢)? –