C# Directory.GetFiles with mask

2019-09-17 11:08发布

问题:

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));