Friday, January 10, 2014

Opening File in exclusive or shared mode

Sometimes you need to read file that can be used by other processes as well and in that case you if you just want to read the content of the file and let the other process to write in it, you actually have to open a file in shared mode. Code below can allow you to open a file in shared mode.

"FileShare.ReadWrite" enum allow you to specify the level of lock you want on the file. Here it will allow other processes to read and write to the file/

using (Stream s = new FileStream(fullFilePath,
                                 FileMode.Open,
                                 FileAccess.Read,
                                 FileShare.ReadWrite))
{
  // here use the stream s
}

In case if you don't want other processes to interfere or read your file you can specify "FileShare.None" which will acquire exclusive access to the file.


using (Stream s = new FileStream(fullFilePath,
                                 FileMode.Open,
                                 FileAccess.Read,
                                 FileShare.None))
{
  // here use the stream s
}

 

No comments: