[英]C# Directory.GetFiles with mask
在C#中,我想從與以下掩碼匹配的特定目錄中獲取所有文件:
"myfile_"
xml
即
myfile_4.xml
myfile_24.xml
以下文件不應與掩碼匹配:
_myfile_6.xml
myfile_6.xml_
代碼應該對此有所幫助(也許某些linq查詢可以提供幫助)
string[] files = Directory.GetFiles(folder, "???");
謝謝
我對正則表達式不太滿意,但這可能會有所幫助-
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;
您可以嘗試如下操作:
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
您可以執行以下操作:
Regex reg = new Regex(@"myfile_\d+.xml");
IEnumerable<string> files = Directory.GetFiles("C:\\").Where(fileName => reg.IsMatch(fileName));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.