Search code examples
c#if-statementtry-catch

Check if file exist with Try/Catch


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
}

Solution

  • 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.