2012-07-19 109 views
0

我想檢查我傳遞的目錄中的文件是否具有特定的擴展名。c#遞歸搜索以檢查文件擴展名

public static bool ProcessDirectory(string targetDirectory) 
{ 
    // Process the list of files found in the directory. 
    string[] fileEntries = System.IO.Directory.GetFiles(targetDirectory); 
    foreach (string fileName in fileEntries) 
     if (System.IO.Path.GetExtension(fileName).ToLower().Contains(pattern)) 
      return true; 

    // Recurse into subdirectories of this directory. 
    string[] subdirectoryEntries = System.IO.Directory.GetDirectories(targetDirectory); 
    foreach (string subdirectory in subdirectoryEntries) 
     return ProcessDirectory(subdirectory); 

    return false; 
    } 

通話邀請:

bool foundPattern = false; 
//recursive search - based on search pattern 
if (System.IO.File.Exists(myDirectory) && System.IO.Path.GetExtension(myDirectory).Contains(pattern)) 
{ 
    // This path is a file 
    foundPattern = true; 
} 
else if (System.IO.Directory.Exists(myDirectory)) 
{ 
    // This path is a directory 
    foundPattern = ProcessDirectory(myDirectory); 
} 

的事情是,我沒有得到的一些結果(我得到的,即使有帶擴展名的文件.xzz假,假設我要求延長.X在搜索模式 - 有時我會變得真實,有時我會變得錯誤)。

如果我步它看起來像我在看目錄,並進入他們遞歸併通過文件去...

但事實並非如此。

+3

使用'GetFiles',做遞歸你過載:'目錄。 GetFiles(「*。x *」,SearchOption.AllDirectories)'。 – vcsjones 2012-07-19 17:56:41

+0

您正在使用的搜索模式是什麼?它是'* .x *'? – 2012-07-19 17:57:41

+1

誰是你模式代碼中的「模式」?我沒有看到它聲明或通過參數 – 2012-07-19 17:58:21

回答

2

我想在你的代碼中的錯誤:

// Recurse into subdirectories of this directory. 
string[] subdirectoryEntries = System.IO.Directory.GetDirectories(targetDirectory); 
foreach (string subdirectory in subdirectoryEntries) 
    return ProcessDirectory(subdirectory); 

應該是這樣的:

// Recurse into subdirectories of this directory. 
string[] subdirectoryEntries = System.IO.Directory.GetDirectories(targetDirectory); 
foreach (string subdirectory in subdirectoryEntries) 
    if (ProcessDirectory(subdirectory)) 
     return true; 

否則你只是將結果返回單個子目錄。 這與您在函數開始時所使用的相同。你第一次做對了。

3

你想要做什麼,可以很容易地與此

string path = @"C:\temp\"; 
string extension = "*.txt"; 
var files = Directory.GetFiles(path, extension); 

//or recursivly 
var files = Directory.GetFiles(path, extension, SearchOption.AllDirectories); 

你的情況來進行:

public static bool ProcessDirectory(string startPath, string pattern) 
{ 
    return Directory.GetFiles(startPath, pattern, SearchOption.AllDirectories).Any(); 
}