问题描述
在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));
问题描述
In C#, I would like to get all files from a specific directory that matches the following mask:
- prefix is "myfile_"
- suffix is some numeric number
- file extension is xml
i.e
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)
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
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));
相关问答
相关标签/搜索