2012-06-05 172 views
6
string fileName = ""; 

      string sourcePath = @"C:\vish"; 
      string targetPath = @"C:\SR"; 

      string sourceFile = System.IO.Path.Combine(sourcePath, fileName); 
      string destFile = System.IO.Path.Combine(targetPath, fileName); 

      string pattern = @"23456780"; 
      var matches = Directory.GetFiles(@"c:\vish") 
       .Where(path => Regex.Match(path, pattern).Success); 

      foreach (string file in matches) 
      { 
       Console.WriteLine(file); 
       fileName = System.IO.Path.GetFileName(file); 
       Console.WriteLine(fileName); 
       destFile = System.IO.Path.Combine(targetPath, fileName); 
       System.IO.File.Copy(file, destFile, true); 

      } 

我上面的程序運行良好,只有一個模式。在目錄c#中查找匹配模式的文件?

我正在使用上面的程序來查找與匹配模式的目錄中的文件,但在我的情況下,我有多個模式,所以我需要在string pattern變量中傳遞多個模式作爲數組,但我沒有想法如何我可以在Regex.Match中操縱這些模式。

任何人都可以幫助我嗎?

回答

9

你可以把一個正則表達式

string pattern = @"(23456780|otherpatt)"; 
+0

完美的傢伙,thankss! –

1

在可以例如

string pattern = @"(23456780|abc|\.doc$)"; 

這將匹配文件蒙山您choosen模式或做最簡單的形式帶有abc模式的文件或擴展名爲.doc的文件

模式參考av ailable的正則表達式類可能是found here

4

變化

.Where(path => Regex.Match(path, pattern).Success); 

.Where(path => patterns.Any(pattern => Regex.Match(path, pattern).Success)); 

在圖形是IEnumerable<string>,例如:

string[] patterns = { "123", "456", "789" }; 

如果你有更多然後15表達式,您可能想要增加緩存大小:

Regex.CacheSize = Math.Max(Regex.CacheSize, patterns.Length); 

參見http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.regex.cachesize.aspx瞭解更多信息。

+0

應該是'Regex.Match(System.IO.File.GetFileName(path),pattern)',因爲'GetFileNames'返回完整路徑。 –

2

Aleroot的回答是最好的,但如果你想要做它在你的代碼,你也可以做這樣的:

string[] patterns = new string[] { "23456780", "anotherpattern"}; 
     var matches = patterns.SelectMany(pat => Directory.GetFiles(@"c:\vish") 
      .Where(path => Regex.Match(path, pat).Success)); 
+0

這是非常低效的,因爲Directory.GetFiles()調用將在每個模式中執行一次。如果你逆轉這些操作會更好:Directory.GetFiles(...)。SelectMany(file => patterns)... 但是,如果它們恰好匹配兩個表達式,它們都會返回同一個文件兩次。看到我的答案找不到這樣做的解決方案,並且因此效率更高(只要匹配一個模式就會停止匹配) –

+0

的確 - 使用正則表達式處理它是迄今爲止最好的解決方案 - 與已經提到:) – Nathan

相關問題