1

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

1 Answer 1

3

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();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.