kevindaub
kevindaub

Reputation: 3363

File.Delete Not Deleting the File

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

Upvotes: 20

Views: 31762

Answers (6)

user3856437
user3856437

Reputation: 2387

It could also be that the file is being used by one of your objects. Like in my case, I use the location path to attach the file for my email program. I have to release or set the object to null or dispose() it to release the file.

Attachment attachment;
attachment = new Attachment(filepath);
mail.Attachments.Add(attachment);

SmtpServer.Dispose();
attachment = null;
mail.Dispose();
GC.Collect();

foreach (string filepath in files)
    File.Delete(filepath);

Upvotes: 0

David Galanti
David Galanti

Reputation: 1

Another example could be that the delete request is in a kind of queued state. For example when the file has been locked because it has not yet been closed after being edited by another process. If that is the case you can alter that process to close the file properly or kill the process and the file disappears.

Upvotes: 0

Eli
Eli

Reputation: 444

Another possibility is that the file is still in use by some background process. Then it does not fail but it does not delete the file.

Upvotes: 4

Mitch Wheat
Mitch Wheat

Reputation: 300797

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); 
} 

Upvotes: 23

Andy West
Andy West

Reputation: 12507

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.

Upvotes: 4

BFree
BFree

Reputation: 103770

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?

Upvotes: 2

Related Questions