1

I am trying to stop all other processes from reading and writing to a file so I need to synchronize between process,how can I do it?

It will be helpful if someone will give me a pattern for it, and show me where should I enter the read and write section in the code.

rene
  • 41,474
  • 78
  • 114
  • 152
Dor Bracha
  • 11
  • 1
  • 2
    Are all those other processes owned by you? As in you have the source code and can add locking constructs to them? – rene Jul 30 '15 at 11:46
  • 1
    Wouldn't this be simply opening the file with exclusive locks, this would prevent any other process from opening the file. – Lasse V. Karlsen Jul 30 '15 at 11:48

1 Answers1

1

Alright. Easy thing thought if that's your aim. You can use a filestream to open up your file. Like..

using (var stream = new FileStream(
                            @"C:\files\yourFile.txt", 
                            FileMode.Open, 
                            FileAccess.ReadWrite, 
                            // that's the important parameter to set
                            // it locks the file from other processes
                            // as long as the stream persists
                            FileShare.None)) {
    // give it some logic ...
}

Messed up. Didn't note the questions intention, my bad. If you try to close a process from reading/writing to a file. Try to find out which and kill it.

Community
  • 1
  • 1
Jan Unld
  • 370
  • 1
  • 10
  • Will this work if other process have the file already open with a similar fileaccess/fileshare setting? – rene Jul 30 '15 at 11:56
  • According to the [Microsoft Documentation](https://msdn.microsoft.com/en-US/library/system.io.fileshare%28v=vs.110%29.aspx) for this enum. All other attempts (locally or remotly from another process) should fail – Jan Unld Jul 30 '15 at 12:05
  • I know but your code would fail if some other process have already opened yourfile.txt with the same arguments... – rene Jul 30 '15 at 12:10
  • So there are two ways you could handle that. 1st.. Wait till the process that's locking the file unlocks it. Or 2nd.. find out which process locks the file and kill it. Can't see any other way to deal with that problem. – Jan Unld Jul 30 '15 at 12:18