C# Directory.GetFiles with mask

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-13 04:29:10

问题


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


回答1:


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;



回答2:


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



回答3:


You can do something like:

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

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


来源:https://stackoverflow.com/questions/16664756/c-sharp-directory-getfiles-with-mask

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!