tags:

views:

58

answers:

2

I want to delete a file that may or may not exist. I write

try { File.Delete(temp); } catch { }

Is there an easier way? Also I realize this ignores other exceptions as well but i dont care in this case.

+6  A: 
try
{
    if(File.Exists(temp))
       File.Delete(temp);

}
catch(IOException e)
{
   // file is in use
}
catch(UnauthorizedAccessException ex)
{
   // read only
   // no permissions
}

More can be found on the MSDN page for File.Delete

PostMan
No need to check for existence...
jball
Ha, did not know that. But defensive programming, and in case you want to do other stuff if the file exists (like remove from a list)
PostMan
In the spirit of defensive programming, doing a catch for `UnauthorizedAccessException`s or `IOException`s would probably be warranted.
jball
No doubt, I shall update
PostMan
just want to notice that the code in the `try` body is affected to race condition
zerkms
it is indeed, how would you get around it? You need to check the file exists before you can do anything to the file? Is that not correct?
PostMan
@PostMan: No you don't ;-) Just try the action in question, and deal with the error (exception) when it occurs. Or do check before you attempt - eventually presenting a "better" error message - but be prepared that the actual operation may still fail later.
Christian.K
Oh I still have so much more to learn! :)
PostMan
+6  A: 

No need for the try catch block to handle a non-existant file. The File.Delete method does not throw an exception if the file does not exist. From MSDN:

If the file to be deleted does not exist, no exception is thrown.

jball
NB. it will throw exceptions if the path is wrong
RobS
I'd usually vote that up for brevity, but that is not to say that Delete never throws an exception, If the path specified is invalid, for example, Delete will raise an exception.
Jim Brissom
There are a few other exceptions to watch for, e.g. if the files in use or it's an XP or before system and there's an open file handle.
jball
Edited for clarity about why the `try catch` block in the question does not accomplish what the questioner thought it did.
jball
Corrected. What happened was i forgot to create the folder first where the temp file usually resides in. Thus the exception. Oops.
acidzombie24