Home > Software engineering >  How to fetch a particular filename pattern from directory
How to fetch a particular filename pattern from directory

Time:12-17

I'm trying to fetch a particular filename from a directory. The code I've tried is as below

DirectoryInfo dirInfo = new DirectoryInfo(directoryPath);
FileInfo recentlyModLogFile = (from files in dirInfo.GetFiles("^Monarch_[0-9]{2}$") orderby files.LastWriteTime descending select files).First();
//Output : Error

List of file names (Input)

Monarch_05bridge  //Date modified 16-12-2021 20:41
Monarch_04bridge  //Date modified 16-12-2021 06:49
Monarch_04  //Date modified 16-12-2021 05:39
Monarch_02  //Date modified 16-12-2021 05:49
Monarch_02bridge  //Date modified 14-12-2021 19:34
Monarch_01  //Date modified 14-12-2021 09:08

Code should look for files whose filename starts with Monarch_ followed by 2 numeric digits and then filter out the recently modified file

So the output should be Monarch_02

I also tried doing

DirectoryInfo dirInfo = new DirectoryInfo(directoryPath);
FileInfo recentlyModLogFile = (from files in dirInfo.GetFiles(Monarch_   "*") orderby files.LastWriteTime descending select files).First();
//OUtput : Monarch_05bridge 

Can someone help me to resolve this issue.

CodePudding user response:

You can use Regular Expressions to achieve this.

var regex = new Regex(@"Monarch _\d\d");
if(regex.IsMatch(fileName))
{
   //you got your file
}

CodePudding user response:

string youngestFile = Directory.GetFiles(directoryPath)
.Where(o => Regexp.Contains(Path.GetFileNameWithoutExtension(o), "Monarch_\\d\\d"))
.OrderByDescending(o => File.GetLastWriteTime(o))
.FirstOrDefault();

This is a quick copy-and-paste from my project files. The Regexp.Contains() is one of the simple methods I wrote to do regexp comparisons.

Notice the Regular Expression I used allow Monarch_02, Monarch_02Bridge and abcMonarch_09 all to be possible result. You can use "^Monarch_\\d\\d$", if you want a strict rule.

Refer to Regular Expressions for details.

private static Match GetFirstMatch(string text, string pattern)
{
   Match match = Regex.Match(text, pattern, RegexOptions.None);
   return match;
}

public static Boolean Contains(string text, string pattern)
{
   return GetFirstMatch(text, pattern).Value != String.Empty;
}

Basically, use Directory.GetFiles(path) to get all the files, then use LINQ to apply conditions, order-bys and fetch the first result.

The Path, Directory and File classes can help a lot when you are working around file system.

  • Related