Search code examples
c#.netprocessfile-locking

Lock file by one process


I have an application which runs multiple processes at the same time for reading and writing to file.

private Process PrepareProcess(string workingDirName, string scriptPath, string[] args) {
    var process = new Process {
        StartInfo = {
            WorkingDirectory = workingDirName,
            FileName = scriptPath,
            Arguments = string.Format(string.Join(" ", args))
        }
    };
    return process;
}

I need to be sure that file will be modified only by one process at a time. How can I do that?

The process will run an external script which will the modify file. I can't manage to open the file. I need to manage running process.


Solution

  • You can use "Named Mutex". It helps you to say "Hey wait, am working on with that file!". It is your call you can wait or ignore that file.

    Take a look at Mutex class

    Also worth noting that by default if you open a file, FileShare will be None which means don't share access with anyone till I close the file. So it will fail when attempt to access in another process. You can't modify it simultaneously. To prevent that failure and handling exception and all using "Mutex" is a elegant way.