File.Delete doesn't throw error when the file doesn't exist

12,731

File.Delete on MSDN:

public static void Delete(string path)

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

So. it's deliberated.... no true \ false and no exceptions, just delete the file if it exist.

Note about File.Exist:

public static bool Exists(string path)

Return Value Type: System.Boolean

true if the caller has the required permissions and path contains the name of an existing file; otherwise, false. This method also returns false if path is Nothing, an invalid path, or a zero-length string. If the caller does not have sufficient permissions to read the specified file, no exception is thrown and the method returns false regardless of the existence of path.

MSDN

Share:
12,731
user740144
Author by

user740144

Updated on July 27, 2022

Comments

  • user740144
    user740144 over 1 year

    Strange problem occurs on the production platform (64 bit win 2008 server). It is connected with File.Exists and File.Delete methods...

    On test platform in debug (win xp), etc it works fine. On Server 2008 for the first few times
    File.Exists reported true for the file which didn't exist ...

    When I Was doing further tests File.Exists finally reported false for the file which didn't exist.
    But File.Delete hadn't thrown any error when attempting to delete the file which didn't exists ...

    What is happening ... ?

    I read somewhere that system virtualation could mess the things up ... but hasn't found any file in: %userprofile%\AppData\Local\VirtualStore

  • user740144
    user740144 about 12 years
    My mistake, when I Was testing the File.Delete method on my machine the error I got was that it couldn't find the path specified in the parameter, that's why I got the impression that it is because the file didn't exist. But obviously it works as you wrote @gdoron. Thank You.
  • AaronLS
    AaronLS almost 10 years
    Yes, if the directory part of the path does not exist, an exception is thrown.
  • Pogrindis
    Pogrindis about 3 years
    Yup, to double down, if the directory is bad, it will throw an exception. - Which is a bit strange.. But if it had to validate the dir too, it would take longer.