[英]C# Directory.GetFiles with mask
In C#, I would like to get all files from a specific directory that matches the following mask: 在C#中,我想从与以下掩码匹配的特定目录中获取所有文件:
"myfile_"
"myfile_"
xml
xml
ie 即
myfile_4.xml
myfile_24.xml
the following files should not match the mask: 以下文件不应与掩码匹配:
_myfile_6.xml
myfile_6.xml_
the code should like somehing this this (maybe some linq query can help) 代码应该对此有所帮助(也许某些linq查询可以提供帮助)
string[] files = Directory.GetFiles(folder, "???");
Thanks 谢谢
I am not good with regular expressions, but this might help - 我对正则表达式不太满意,但这可能会有所帮助-
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;
You can try it like: 您可以尝试如下操作:
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);
}
}
So if your Test folder has files: 因此,如果您的“测试”文件夹中包含文件:
myfile_24.xml
MyFile_6.xml
MyFile_6.xml_
myfile_ABC.xml
_MyFile_6.xml
Then you will get in selectedFiles
然后您将进入
selectedFiles
myfile_24.xml
MyFile_6.xml
You can do something like: 您可以执行以下操作:
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.