2

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

4
  • 3
    I would just loop through the results and apply my own logic to determine if I should process it or not. Obviously the file type filter is easy enough to apply to the GetFiles, then do the extra testing in the loop
    – musefan
    May 21, 2013 at 7:50
  • Yes you should be able to use "myfile_*.xml" in the GetFiles() to vastly reduce the number of filenames returned, and then provide an extra filter using a regexp. May 21, 2013 at 7:55
  • @cheedep That's a different question. He's not asking for multiple filters. May 21, 2013 at 7:55
  • Also in stackoverflow.com/questions/1669892/… May 21, 2013 at 7:56

3 Answers 3

7

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
  • i am getting exception 'illegal characters in path' when running this code. how come?
    – user829174
    May 21, 2013 at 8:35
  • edited the answer to put the folder in the Directory.Getfiles() method. Sorry, missed it earlier.
    – siddharth
    May 21, 2013 at 8:40
1

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
1

You can do something like:

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

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.