tags:

views:

322

answers:

3

I am trying to delete a file, but the following code doesn't do that. It doesn't throw an exception, but the file is still there. Is that possible?

try
{
    File.Delete(@"C:\File.txt");
} 
catch(Exception e)
{
    Console.WriteLine(e);
}

If the file can't be deleted, the exception should print out, but it doesn't. Should this fail silently (as in the File.Delete method is swallowing any errors)?

+6  A: 

File.Delete does not throw an exception if the specified file does not exist. [Some previous versions of the MSDN documentation incorrectly stated that it did].

try 
{ 
    string filename = @"C:\File.txt";
    if (File.Exists(filename))
    { 
        File.Delete(filename);
    }
    else
    {
        Debug.Writeline("File does not exist!");
    } 
}  
catch(Exception e) 
{ 
    Console.WriteLine(e); 
} 
Mitch Wheat
@Mitch » I don't think that's right. From the second sentence of MSDN: "_An exception is not thrown_ if the specified file does not exist." http://msdn.microsoft.com/en-us/library/system.io.file.delete.aspx
John Feminella
Interesting, I will have to do a File.Exists before the delete to verify this. Thanks.
daub815
you are correct; the 3.5 doco is correct. some previous versions were not.
Mitch Wheat
@John Feminella: Thanks: I have corrected.
Mitch Wheat
+1  A: 

Are you sure the file name is correct? The only time it doesn't throw an error is if the file doesn't exist. Stupid question, but do you by any chance have a typo in the file name? Or an error in the path?

BFree
+2  A: 

Check to see that the file's path is correct. An exception will not be thrown if the file does not exist. One common mistake is to confuse a file named File.txt with one named File.txt.txt if "Hide extensions for known file types" is set in Windows.

Andy West