Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

File.Delete Not Deleting the File

Tags:

c#

.net

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)?

like image 708
kevindaub Avatar asked Jan 08 '10 04:01

kevindaub


2 Answers

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); 
} 
like image 116
Mitch Wheat Avatar answered Sep 22 '22 08:09

Mitch Wheat


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.

like image 45
Andy West Avatar answered Sep 23 '22 08:09

Andy West