Select Files From Folder Depending on Name Convention

66 views Asked by At

I receive a bunch of XML files in a folder.

I want to keep checking for files that have the following naming convention:

sr-{first_id}-{second_id}-matchresults.xml

To parse as soon as I receive one.

For example:

sr-40-24-standings.xml
sr-40-24-results.xml
sr-40-24-j7844-matchresults.xml

I should select that one : sr-40-24-j7844-matchresults.xml

What comes after this that helps me select Files depending on their naming convention from a ASP Web Service?

 Dim files As IO.FileInfo() = FolderName.GetFiles("*.xml")
2

There are 2 answers

0
Anjali_RVS On BEST ANSWER
private bool IsValid(string value)
    {
        string regexString = "^sr-([a-z0-9]+)-([a-z0-9-]+)-matchresults.xml";
        return Regex.IsMatch(value, regexString);
    }

This method will give you the files with the specified format (sr-{first_id}-{second_id}-matchresults.xml). Note: your Ids can contain alphanumeric characters also "-" symbol. if you don't want that symbol in id, then code will look like,

string regexString = "^sr-([a-z0-9]+)-([a-z0-9]+)-matchresults.xml";
5
DotNetMatt On

You can use a regular expression:

var pattern = new Regex(@"^sr-.............$");

And then apply a "filter" on Directoy.GetFiles to retrieve only the files matching this pattern:

var files = Directory.GetFiles("path to files", "*.xml").Where(path => pattern.IsMatch(path)).ToList();