MSDN tells us that when you call "File.Delete( path );" on a file that doesn't exist an exception is generated.
Would it be more efficient to call the delete method and use a try/catch block to avoid the error or validate the existence of the file before doing the delete?
I'm inclined to think it's better to avoid the try/catch block. Why let an error occur when you know how to check for it.
Anyway, here is some sample code:
// Option 1: Just delete the file and ignore any exceptions
/// <summary>
/// Remove the files from the local server if the DeleteAfterTransfer flag has been set
/// </summary>
/// <param name="FilesToSend">a list of full file paths to be removed from the local server</param>
private void RemoveLocalFiles(List<string> LocalFiles)
{
// Ensure there is something to process
if (LocalFiles != null && LocalFiles.Count > 0 && m_DeleteAfterTransfer == true)
{
foreach (string file in LocalFiles)
{
try { File.Delete(file); }
catch { }
}
}
}
// Option 2: Check for the existence of the file before delting
private void RemoveLocalFiles(List<string> LocalFiles )
{
// Ensure there is something to process
if (LocalFiles != null && LocalFiles.Count > 0 && m_DeleteAfterTransfer == true)
{
foreach (string file in LocalFiles)
{
if( File.Exists( file ) == true)
File.Delete(file);
}
}
}
Some Background to what I'm trying to achieve: The code is part of an FTP wrapper class which will simplify the features of FTP functionality to only what is required and can be called by a single method call. In This case, we have a flag called "DeleteAfterTransfer" and if set to true will do the job. If the file didn't exists in the first place, I'd expect to have had an exception before getting to this point. I think I'm answering my own question here but checking the existence of the file is less important than validating I have permissions to perform the task or any of the other potential errors.