Question

Language used: C#

Theory: I want to create a file with the flag FileOptions.DeleteOnClose in a temporary folder. The file is successfully created and I write dato onto it, the next step is to launch the application associated with the file Process.Start(...) and allow the user to inspect the document, finally I close my handle and as soon as other process close the handle to the temporary file, the file is deleted by operating system.

My problem is that other processes cannot open the file, even for reading, despite if I add FileShare.ReadWrite | FileShare.Delete to the sharing mode.

Any suggestions?

Was it helpful?

Solution

The other processes need to specify FileShare.Delete when they open the DeleteOnClose file

From the MSDN CreateFile docs:

"FILE_FLAG_DELETE_ON_CLOSE... Subsequent open requests for the file fail, unless the FILE_SHARE_DELETE share mode is specified."

OTHER TIPS

Check this:

You need to make sure that all processes are opening the file with FileShare.ReadWrite and FileShare.Delete.

Even if the creator opens with share-readwrite, if a second program tries to open with share-read, the second program is basically saying no-one else can write. But the first program already has that power so the second open fails.

Switch to Linux scnr

Ok, seriously now: That is a flaw in the Windows operating system which can't really be worked around. Each program opening the file must agree on other programs having the file open in the same time. That was a problem I got many years back when I still used Windows as well. It doesn't suffice to open a file and say: Let anyone else open this as well. The others must also say open this file even if it's open already.

On Linux on the contrary, the operating system doesn't allow any file locking in the way Windows does at all. Here, if any file is used by more than one program simultaneously, the programs itself must make sure, that concurrent accesses get locked out. Additionally, on Linux, we can just create the file, make sure the other process has been started and opened the file and then just delete the file (while it is open). The filename is then removed from the file system immediatelly, but the file is still maintained by the file system driver until the last link (including open file handles) got removed.

Back to your problem: As all of this doen't work on Windows, you could do two other approaches:

  1. Register the file to be deleted on next boot (in the Win3x days, there was a section in the win.ini for that. Newer Windows version still support that, I just can't recall any longer, how it's done now).
  2. Start the other process, wait for it to open the file, close the file and then try each minute to delete the file until deletion succeeds ...

Regards, Bodo

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top