C# detect if File.OpenText fails

Posted on 2009-02-17
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...
Question by:ehensens
    LVL 9

    Accepted Solution

    Read here:

    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"
    LVL 19

    Expert Comment

    The method will raise a FileNotFoundException exception if it does not find the specified file
    LVL 19

    Expert Comment

    Alternatively you can use the Exists method of the File object to check if a file exists.
    if (File.Exists("file.txt")) {

    Open in new window


    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    How your wiki can always stay up-to-date

    Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
    - Increase transparency
    - Onboard new hires faster
    - Access from mobile/offline

    In order to hide the "ugly" records selectors (triangles) in the rowheaders, here are some suggestions. Microsoft doesn't have a direct method/property to do it. You can only hide the rowheader column. First solution, the easy way The first sol…
    This article introduced a TextBox that supports transparent background.   Introduction TextBox is the most widely used control component in GUI design. Most GUI controls do not support transparent background and more or less do not have the…
    The viewer will learn how to use NetBeans IDE 8.0 for Windows to connect to a MySQL database. Open Services Panel: Create a new connection using New Connection Wizard: Create a test database called eetutorial: Create a new test tabel called ee…
    The viewer will learn how to synchronize PHP projects with a remote server in NetBeans IDE 8.0 for Windows.

    759 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

    Need Help in Real-Time?

    Connect with top rated Experts

    11 Experts available now in Live!

    Get 1:1 Help Now