Home > Blockchain >  How to handle linq statement returning exception when no file found
How to handle linq statement returning exception when no file found

Time:06-02

I have this code to fetch the recently modified file

DirectoryInfo dirInfo = new DirectoryInfo(directoryPath);
string partialFileName = "partialFileName";
FileInfo recentlyModFile = (from files in dirInfo.GetFiles(partialFileName   "*") orderby files.LastWriteTime descending select files).First();

Concern is that when there is no file that matches the criteria then it returns exception which obviously is bound to happen and I am looking for ways to handle the same.

I tried putting the above piece of code in try catch block but that didn't help. It would be helpful if someone can let me know how to fix this.

Thank you

CodePudding user response:

You can use FirstOrDefault() instead of First()

First() will throw an exception if there is no result data.

FirstOrDefault() returns the default value (null) if there is no result data.

FileInfo recentlyModFile = (from files in dirInfo.GetFiles(partialFileName   "*") orderby files.LastWriteTime descending select files).FirstOrDefault();
  • Related