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

C# detect if File.OpenText fails

Hi all,

Is there some way to determine if my attempt to File.OpenText("file.txt") fails, i.e. "file.txt" does not exist? I know it's so simple in C...
  • 2
1 Solution
Rob SiklosCommented:
Read here: http://msdn.microsoft.com/en-us/library/system.io.file.opentext.aspx

If something goes wrong (e.g. file not found), an exception will be thrown.  

So, you should call File.OpenText() in a "try" statement, and handle the exception in a "catch"
The method will raise a FileNotFoundException exception if it does not find the specified file http://msdn.microsoft.com/en-us/library/system.io.file.opentext.aspx
Alternatively you can use the Exists method http://msdn.microsoft.com/en-us/library/system.io.file.exists.aspx of the File object to check if a file exists.
if (File.Exists("file.txt")) {

Open in new window

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.

Join & Write a Comment

Featured Post

Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

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