使用Try/Catch检查文件是否存在

3D-*_*tiv 3 c# if-statement try-catch

我是关于Try/Catch的新手.在下面的代码中,我有一个简单的测试来检查文件是否存在.在我的C#课程中,我必须使用Try/Catch,我不知道如何使用它,我是否仍然在Try部分中使用if语句,或者是否有更好的方法来检查文件是否存在在里面试试?如果文件是简单的txt文件或序列化文件,有什么区别吗?

if (File.Exists("TextFile1.txt"))
{
   MessageBox.Show("The file don't exist!", "Problems!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
Run Code Online (Sandbox Code Playgroud)

我必须使用Try/Catch方式

try
{
code to check if file exist here
}
catch
{
error message here
}
Run Code Online (Sandbox Code Playgroud)

Aks*_*oop 10

try
{
 if (!File.Exists("TextFile1.txt"))
    throw new FileNotFoundException();
}
catch(FileNotFoundException e)
{
   // your message here.
}
Run Code Online (Sandbox Code Playgroud)


Hab*_*bib 6

如果要在不使用的情况下检查文件是否存在File.Exist,则可以尝试在try块中打开该文件,然后捕获异常FileNotFoundException.

try
    {
        // Read in non-existent file.
        using (StreamReader reader = new StreamReader("TextFile1.txt"))
        {
        reader.ReadToEnd();
        }
    }
catch (FileNotFoundException ex)
    {
        MessageBox.Show("The file don't exist!", "Problems!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
        // Write error.
        Console.WriteLine(ex);
    }
Run Code Online (Sandbox Code Playgroud)


Sid*_*med 6

试试这个 :

try
{
   if(!File.Exist("FilePath"))
       throw new FileNotFoundException();

   //The reste of the code
}
catch (FileNotFoundException)
{
    MessageBox.Show("The file is not found in the specified location");
}
catch (Exception ex)
{
    MessageBox.Show(ex.Message);
}
Run Code Online (Sandbox Code Playgroud)

  • 捕获特定异常..:D (2认同)