在C#中,我想从特定目录中获取与以下掩码匹配的所有文件:
"myfile_"
xml
即
myfile_4.xml
myfile_24.xml
以下文件与掩码不匹配:
_myfile_6.xml
myfile_6.xml_
代码应该喜欢这个(也许一些linq查询可以帮助)
string[] files = Directory.GetFiles(folder, "???");
由于
答案 0 :(得分: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;
答案 1 :(得分:1)
您可以尝试:
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);
}
}
因此,如果您的Test文件夹包含文件:
myfile_24.xml
MyFile_6.xml
MyFile_6.xml_
myfile_ABC.xml
_MyFile_6.xml
然后你会进入selectedFiles
myfile_24.xml
MyFile_6.xml
答案 2 :(得分:0)
您可以执行以下操作:
Regex reg = new Regex(@"myfile_\d+.xml");
IEnumerable<string> files = Directory.GetFiles("C:\\").Where(fileName => reg.IsMatch(fileName));