Runtime: Directory.CreateDirectory returns success without creating directory after Directory.Delete

Created on 27 Aug 2019  路  3Comments  路  Source: dotnet/runtime

When I have a non empty directory, createdirectory does not create directory after delete.

public void SetupRootPath(string path) { Directory.CreateDirectory(path); Directory.Delete(path, true); Directory.CreateDirectory(path); }

wondering if Directory.Delete is really a synchronous call?

.Net Version : .net core 2.2
Platform: windows 10

area-System.IO

Most helpful comment

@sameerkattel Which Windows 10 build are you using? Delete has never been truly synchronous, it would simply mark the file/directory for deletion. The file/directory would not be removed until all handles are closed. When you make these calls quickly in succession what typically happens is this:

  1. You create the directory
  2. Antivirus or indexing opens a handle to the new directory
  3. You mark the directory for deletion (this is just the way Windows works- there is no "force")
  4. You try to create the same directory, we see that it still exists (as a handle was still open), and return with no issues.
  5. When the final handle gets closed, Windows actually deletes the directory.

In Windows 10 1903 deletion was changed so that it immediately moves the entry to a hidden location, freeing up the name for use again. While this particular issue you're seeing shouldn't happen anymore, it's still a bad pattern to use as all prior versions of Windows do this and some apps may opt to turn on the old behavior for compatibility.

All 3 comments

cc: @JeremyKuhne

@sameerkattel Which Windows 10 build are you using? Delete has never been truly synchronous, it would simply mark the file/directory for deletion. The file/directory would not be removed until all handles are closed. When you make these calls quickly in succession what typically happens is this:

  1. You create the directory
  2. Antivirus or indexing opens a handle to the new directory
  3. You mark the directory for deletion (this is just the way Windows works- there is no "force")
  4. You try to create the same directory, we see that it still exists (as a handle was still open), and return with no issues.
  5. When the final handle gets closed, Windows actually deletes the directory.

In Windows 10 1903 deletion was changed so that it immediately moves the entry to a hidden location, freeing up the name for use again. While this particular issue you're seeing shouldn't happen anymore, it's still a bad pattern to use as all prior versions of Windows do this and some apps may opt to turn on the old behavior for compatibility.

@JeremyKuhne I see. Thanks for the info! Btw here is my windows specifications:

Version 1903
OS Build 18362.295

Was this page helpful?
0 / 5 - 0 ratings