0

I am doing a simple thing with files on network shared folder, within Windows:

CreteFile (new file)
DeleteFile (old file)
MoveFile (from new file name to old)

This works for most files in the shared folder, but for two I get error "File already exists" on MoveFile command. What is happening here? I tried googling for clues, but didn't find anything so far. I do this in C#, but this shouldn't matter.

Network folder is part of the web site. But even if I restart IIS the problem persists, with the same two files.

Also, overwriting the files directly still works. In fact that was the previous solution, and I wanted to improve on it, because files may become corrupted if the copy operation fails in the middle of the copying.

Dialecticus
  • 16,400
  • 7
  • 43
  • 103
  • 1
    [`DeleteFile`](https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-deletefile): *"The `DeleteFile` function marks a file for deletion on close. Therefore, the file deletion does not occur until the last handle to the file is closed."* – IInspectable Sep 26 '22 at 09:34
  • @IInspectable this seems to be the problem. IIS locks the files in a way that writing is allowed, but deletion is not. Could you please post an answer so that I can close the question? – Dialecticus Sep 26 '22 at 13:42
  • I already [have](https://stackoverflow.com/a/25421332/1889329). – IInspectable Sep 26 '22 at 14:11

1 Answers1

0

IIS keeps a handle to the file, because the file is currently in use. File.Delete succeeds, but the file is only marked for deletion, and will be deleted once IIS closes the handle. This may happen very late, or in fact never (or rather until IIS is reset).

Instead of trying to delete an open file you should do something else to replace it. What would that be is a different question.

Dialecticus
  • 16,400
  • 7
  • 43
  • 103