Pages

Wednesday, April 12, 2017

How to open a file locked by other process

Trying to open a file which is being used by another process will result in an exception.

For example, when we try to open a word document opened and locked by other process, we will get an exception.

Here is the sample code that results in exception:
 using (FileStream fs = new FileStream(fileToUpload, FileMode.Open, FileAccess.Read))  
 {  
  fileContents = new Byte[fs.Length];  
  fs.Read(fileContents, 0, Convert.ToInt32(fs.Length));  
 }  

Inorder to resolve this,

we need to use another overload of the FileStream constructor.

Just add FileShare.ReadWrite to the parameters.
 using (FileStream fs = new FileStream(fileToUpload, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))  
 {  
 fileContents = new Byte[fs.Length];  
 fs.Read(fileContents, 0, Convert.ToInt32(fs.Length));  
 }  
This overload of the FileStream constructor allows to open a file in a non-exclusive mode.

No comments:

Post a Comment