Search code examples
c#filedirectoryatomic

How to atomically create a file in a non-existing folder?


Given a path to a file, I would like to create this file, and the string of directories leading to it if they don't exist ; but I don't want any other instance of my program to be able to see the base directory existing without the file in it.

Basically, I want to atomically create the required directories and the file at once. From what I understood, it must be done in 2 steps (create directory, create file), so I was thinking about using a lock file, but the same problem applies : where do I create the lock file ? I don't know how many levels of folders need to be created, and at some point down the path, I might loose writing rights, so there is no "safe place" for a lock file.

Then I thought about using a lock directory instead of a lock file, but I couldn't find any "test and set" method to create directories (Directory.CreateDirectory(path) doesn't tell you if it did something).

So what's the right way to do it ?


Solution

  • Create the directory and file under a temporary name and atomically rename the directory to the final name.

    Or use transactional NTFS (much harder).