Tuesday, December 23, 2008

Write locked - read shared file

I wanted to open/create a file in one process which locks it for writing but shared for reading which another process can open for reading. It took a while to me. The code is given below:

1) Open a file locked for writing but shared for reading:
FileStream stream = new FileStream(@"C:\Myfile.txt", FileMode.Open, FileAccess.ReadWrite, FileShare.Read);

2) In another process/thread, open the file for read (not writing) and readwrite sharing
FileStream stream = new FileStream(@"C:\Myfile.txt", FileMode.Open, FileAccess.Read, FileShare.ReadWrite)