C# Handling file not found exceptions - a better way?

I am writing a small app that opens text files, searches for a keyword, then displays it. The problem is if one of the files does not exist I get a nasty exception error. I found a way to confirm the file exists and then not execute that code if it does not but is there a catch all or some kind of code I can add to the end of the method that if a file is not there it is no big deal?!

Thanks!
Karl66
Karl66Asked:
Who is Participating?
 
doraiswamyCommented:
if(File.Exists(yourFileName) {
  // open and do whatever you like
}
0
 
bungHocCommented:
Catch all? Put that piece of code into a try - catch block and you have catch all. Ugly though..
0
 
Karl66Author Commented:
Are you suggesting I confirm that every file I want to attempt to access I check for its very esistence first ... that may be the case. That is my question :)
0
 
bungHocCommented:
Option 1:

You have list of fileNames. Loop through it and check if any of them does not exist, if so, remove those files from that list.

Search and display.

Option 2:

try
{
  // some code of yours, open file, search for keywords etc.
}
catch
{
 // some kind of exceptions if file does not exists etc.
}
0
 
doraiswamyCommented:
Sorry. Should have refreshed page before submitting
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.