Check if file exist with Try/Catch
41,157
Solution 1
You already check on the presence of file in your first sniplet. There is no any need, for this code to be inside try/catch
block.
Solution 2
try
{
if (!File.Exists("TextFile1.txt"))
throw new FileNotFoundException();
}
catch(FileNotFoundException e)
{
// your message here.
}
Solution 3
If you want to check if the file exists without using File.Exist
, then you may try opening the file in a try block, and then catching the exception 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);
}
Solution 4
Try this :
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);
}
Solution 5
Use throw
:
try
{
if (!File.Exists("TextFile1.txt"))
throw (new Exception("The file don't exist!"));
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
Comments
-
3D-kreativ almost 4 years
I'm new to this about Try/Catch. In the code below I have a simple test to check if a file exist. In my task for my C# lesson I must use Try/Catch, and I'm not sure how to use this, should I still use the if statement inside the Try part or is there a better way to do the checking if a file exist inside Try? Is there any difference if the file is a simple txt file or a serialized file?
if (File.Exists("TextFile1.txt")) { MessageBox.Show("The file don't exist!", "Problems!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); }
The Try/Catch way I must use
try { code to check if file exist here } catch { error message here }