?
Solved

C# detect if File.OpenText fails

Posted on 2009-02-17
3
Medium Priority
?
566 Views
Last Modified: 2013-12-14
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...
0
Comment
Question by:ehensens
  • 2
3 Comments
 
LVL 9

Accepted Solution

by:
Rob Siklos earned 1200 total points
ID: 23664393
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"
0
 
LVL 19

Expert Comment

by:LordOfPorts
ID: 23664402
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
0
 
LVL 19

Expert Comment

by:LordOfPorts
ID: 23664421
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

0

Featured Post

[Webinar On Demand] Database Backup and Recovery

Does your company store data on premises, off site, in the cloud, or a combination of these? If you answered “yes”, you need a data backup recovery plan that fits each and every platform. Watch now as as Percona teaches us how to build agile data backup recovery plan.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Update (December 2011): Since this article was published, the things have changed for good for Android native developers. The Sequoyah Project (http://www.eclipse.org/sequoyah/) automates most of the tasks discussed in this article. You can even fin…
This article aims to explain the working of CircularLogArchiver. This tool was designed to solve the buildup of log file in cases where systems do not support circular logging or where circular logging is not enabled
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.
THe viewer will learn how to use NetBeans IDE 8.0 for Windows to perform CRUD operations on a MySql database.
Suggested Courses

569 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question