2013-05-21 15 views
0

在C#Directory.GetFiles,我想從下面的掩碼相匹配的特定目錄中獲取所有文件:C#與面具

  • 前綴是"myfile_"
  • 後綴是一些數字數
  • 文件擴展xml

myfile_4.xml 
myfile_24.xml 

下列文件不應與面膜:

_myfile_6.xml 
myfile_6.xml_ 

代碼想somehing這個這個(也許有些LINQ查詢可以幫助)

string[] files = Directory.GetFiles(folder, "???"); 

感謝

+3

我只是循環查看結果並應用我自己的邏輯來確定是否應該處理它。很顯然,文件類型過濾器很容易應用於'GetFiles',然後在循環中做額外的測試。 – musefan

+0

是的,您應該可以在'GetFiles()'中使用「myfile _ *。xml」以大大減少數量返回文件名,然後使用正則表達式提供額外的過濾器。 –

+0

@cheedep這是一個不同的問題。他沒有要求多個過濾器。 –

回答

3

我用正則表達式不好弄,但是這可能幫助 -

var myFiles = from file in System.IO.Directory.GetFiles(folder, "myfile_*.xml") 
       where Regex.IsMatch(file, "myfile_[0-9]+.xml",RegexOptions.IgnoreCase) //use the correct regex here 
       select file; 
+0

@ I4V - 感謝編輯正則表達式。 :) – siddharth

+0

運行此代碼時,我收到異常'路徑中的非法字符'。怎麼來的? – user829174

+0

編輯了將文件夾放入Directory.Getfiles()方法的答案。對不起,早點錯過了。 – siddharth

0

,您可以嘗試如:

string[] files = Directory.GetFiles("C:\\test", "myfile_*.xml"); 
//This will give you all the files with `xml` extension and starting with `myfile_` 
//but this will also give you files like `myfile_ABC.xml` 
//to filter them out 

int temp; 
List<string> selectedFiles = new List<string>(); 
foreach (string str in files) 
{ 
    string fileName = Path.GetFileNameWithoutExtension(str); 
    string[] tempArray = fileName.Split('_'); 
    if (tempArray.Length == 2 && int.TryParse(tempArray[1], out temp)) 
    { 
     selectedFiles.Add(str); 
    } 
} 

因此,如果您的測試文件夾有文件:

myfile_24.xml 
MyFile_6.xml 
MyFile_6.xml_ 
myfile_ABC.xml 
_MyFile_6.xml 

然後你會在selectedFiles

myfile_24.xml 
MyFile_6.xml 
0

你可以做些什麼像:

Regex reg = new Regex(@"myfile_\d+.xml"); 

IEnumerable<string> files = Directory.GetFiles("C:\\").Where(fileName => reg.IsMatch(fileName));