Ben
Ben

Reputation: 2523

Catch "FileNotFoundException"

I have a method to get the folder path of a particular file:

string filePath = Path.Combine(Environment.GetFolderPath(
               Environment.SpecialFolder.MyDocuments), "file.txt");

And later, I use this to read the text in the file:

StreamReader rdr = new StreamReader(filePath); // "C:\Users\<user>\Documents\file.txt"
        string myString = rdr.ReadToEnd();

Trouble is, if the file doesn't exist, it throws a FileNotFoundException (obviously). I want to hopefully use an if/else to catch the error, in which the user can browse to find the file directly, but I'm not sure what to use to verify if filePath is valid or not.

For example, I can't use:

if (filePath == null)

because the top method to retrieve the string will always return a value, whether or not it is valid. How can I solve this?

Upvotes: 2

Views: 165

Answers (3)

Zohaib Aslam
Zohaib Aslam

Reputation: 595

string filePath = Path.Combine(Environment.GetFolderPath(
               Environment.SpecialFolder.MyDocuments), "file.txt");

if(!File.Exists(filePath))
{
/* browse your file */
}
else
{

        StreamReader rdr = new StreamReader(filePath); // "C:\Users\<user>\Documents\file.txt"
        string myString = rdr.ReadToEnd();
}

Upvotes: 0

F.Buster
F.Buster

Reputation: 88

While File.Exists() is appropriate as a start, please note that ignoring the exception can still lead to an error condition if the file becomes inaccessible (dropped network drive, file opened by another program, deleted, etc.) in the time between the call to File.Exists() and new StreamReader().

Upvotes: 2

Rahul Singh
Rahul Singh

Reputation: 21795

You can use File.Exists:-

if(File.Exists(filePath))
{
  //Do something
}
else
{

}

Upvotes: 1

Related Questions