title: File.Open for read access denied on executing file in Windows
body: <p>I have a problem with file permissions on executing files in Windows that seems to be solved after following a forum tip[1], but I cannot understand why. Maybe you guys can help.</p>
  
  <p>I'm checking the banner of a file by executing it (reading the console output) and then opening the same file for reading afterwards using FileStream:</p>
  
  <pre><code>public void fileMD5(string filename) {
    if (!File.Exists(filename)) return NT.Fail("File does not exist: " + filename);
  
    BinaryReader stream = new BinaryReader(File.Open(filename,
        FileMode.Open, FileAccess.Read, FileShare.ReadWrite));
    int bufferSize = 4096;
    byte[] buffer = new byte[bufferSize];
    int readBytes;
    while ((readBytes = stream.Read(buffer, 0, bufferSize)) &gt; 0) {
      md5Hasher.TransformBlock(buffer, 0, readBytes, buffer, 0);
    }
    stream.Close();
  }
  
  fileMD5('sample.exe');
  </code></pre>
  
  <p>and every once in a while I would get "file is being used by another process". From Wikipedia I know that Windows will set a lock on executing files denying write access[2], but I'm only reading. Also the process should have stopped already when I try to open it.</p>
  
  <p>From the forum post it would seem that adding a FileShare.ReadWrite would help and it seems that It does:</p>
  
  <pre><code>FileStream stream = File.Open('sample.exe', 
      FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
  </code></pre>
  
  <p>But I don't understand why. Is there a race condition here that I don't see?</p>
  
  <p>Also the File.Open call seems to be much quicker with FileShare.ReadWrite instead of the default (which I guess is FileShare.Read).</p>
  
  <p>[1] <a href="http://www.xtremevbtalk.com/archive/index.php/t-192118.html" rel="nofollow">http://www.xtremevbtalk.com/archive/index.php/t-192118.html</a></p>
  
  <p>[2] <a href="http://en.wikipedia.org/wiki/File_locking#In_Microsoft_Windows" rel="nofollow">http://en.wikipedia.org/wiki/File_locking#In_Microsoft_Windows</a></p>