Search code examples
c#filefilelock

C# accessing locked files


I want to access a file via c# which is created and still processed via a different program.
Currently I am copying the file via the Windows explorer to a different location and work then with the copy. As the copy is large I would prefer to work straight with the original file. Is there any way?
The normal FileStream does not allow any shared access mode. I have control over both programs, so I could change the writer as well if neccessary.


Solution

  • You will need to make sure that the program doing the writing and reading have the right FileShare set, so you'll need to pass FileShare.Read into the FileStream constructor for the program writing:

    new FileStream("C:/Users/phil/tmp.txt",FileMode.Create,FileAccess.Write,FileShare.Read)
    

    You will also want to make sure that you have FileShare.ReadWrite enabled for the program that's just reading it in:

    new FileStream("C:/Users/phil/tmp.txt",FileMode.Open,FileAccess.Read,FileShare.ReadWrite)
    

    This will cause the FileStream constructors to put the correct locks on the file itself.

    You can find out more about the constructor on msdn: http://msdn.microsoft.com/en-us/library/5h0z48dh.aspx (there are also other overloads that also take a FileShare parameter)