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 ?
Create the directory and file under a temporary name and atomically rename the directory to the final name.
Or use transactional NTFS (much harder).
You can use the Mutex class which allows you to sync interprocess.
http://msdn.microsoft.com/en-us/library/system.threading.mutex.aspx
In pseudocode for all processes
grab the mutex
try
check or create directory and file
finally
release the mutex
This works for local program instances running on the same pc. Not specified, but for program instances across a network that use the same database you could implement mutex-like functionality in the database.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With