简体   繁体   中英

How to catch a "FileNotFoundException" exception?

I am pretty new to programming and am trying to figure out how to to catch the error "FileNotFoundException." My code is suppose to search for the existing text document (from what is typed into the text box)and load it to my listbox1. I got this problem solved. However, a new problem has arisen! If the user inputs the wrong name/numbers it just crashes the application with the error that it couldn't find the file. Is there any way to get the program to display an error message "File not found." or simply not crash the entire program? Thanks in advance!

     private void btnEnter_Click(object sender, EventArgs e)
    {   
        FileInfo file = new FileInfo(txtExisting.Text + ".txt");
        StreamReader stRead = file.OpenText();
        while (!stRead.EndOfStream)
        {
            listBox1.Items.Add(stRead.ReadLine()); 
        }  
    }

You should use a try-catch statement to handle exceptions.

private void btnEnter_Click(object sender, EventArgs args)
{   
    try
    {
        FileInfo file = new FileInfo(txtExisting.Text + ".txt");
        StreamReader stRead = file.OpenText();
        while (!stRead.EndOfStream)
        {
            listBox1.Items.Add(stRead.ReadLine()); 
        }  
    } 
    catch (FileNotFoundException e)
    {
        // FileNotFoundExceptions are handled here.
    }
}

Basically, the code in the try block will be executed as it would normally be but if an error should arise the catch block will be executed, in particular:

When an exception is thrown, the common language runtime (CLR) looks for the catch statement that handles this exception.

This means that a try-catch statement can have multiple catch blocks if you expect to encounter different types of exceptions so they can be handled accordingly.

More information can be found here .

As for UX, it would be nice to communicate to the user that something went wrong by displaying a message.

Just add a try/catch block with your code in the btnEnter_Click function like this:

try
{
   //your code here
}
catch (FileNotFoundException ex)
{
    MessageBox.Show(ex.Message);//if you want to show the exception message
}
catch (Exception ex1)
{
    /* Exceptions other than the above will be handled in this section,
     this should be used when you are not  aware the type of exception 
     can occur in your code for a safe side*/
}

Using a try/catch statement :

private void btnEnter_Click(object sender, EventArgs e)
{   
    try
    {
        FileInfo file = new FileInfo(txtExisting.Text + ".txt");
        StreamReader stRead = file.OpenText();
        while (!stRead.EndOfStream)
        {
            listBox1.Items.Add(stRead.ReadLine()); 
        }  
    }
    catch (FileNotFoundException ex)
    {
        // Handle exception
    }
}

Use System.IO.File.Exist("path\\\\File.extension");

File.Exists / MSDN It will return a Boolean value, true for File Found and false for File Not Found. Use the try/catch statements when you don't WHAT could cause a problem.

Example:

private void btnEnter_Click(object sender, EventArgs e)
    {   
        if(!System.IO.File.Exists(txtExisting.Text + ".txt")
        {
              MessageBox.Show("File not found");
              return;
        }
        FileInfo file = new FileInfo(txtExisting.Text + ".txt");
        StreamReader stRead = file.OpenText();
        while (!stRead.EndOfStream)
        {
            listBox1.Items.Add(stRead.ReadLine()); 
        }  
    }
        FileInfo file = new FileInfo(txtExisting.Text + ".txt");
        if (!File.Exists(file.FullName))
        {
            Console.WriteLine("File Not Found!");
        }
        else
        {
            StreamReader stRead = file.OpenText();
            while (!stRead.EndOfStream)
            {
                lenter code hereistBox1.Items.Add(stRead.ReadLine());
            }
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM