• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 179
  • Last Modified:

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
0
Karl66
Asked:
Karl66
  • 2
  • 2
1 Solution
 
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:
if(File.Exists(yourFileName) {
  // open and do whatever you like
}
0
 
doraiswamyCommented:
Sorry. Should have refreshed page before submitting
0

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now