title: File.Copy locks source file after completion
body: <p>We are trying to copy a file from a server, down to a local machine in a .NET 2.0 application (C#), but keep having the source file unnecessarily locked. We suspect it is something configured on the file server that is causing this behaviour, but are not sure what ... can you help?</p>
  
  <p>After the file copy operation, the file server (Windows 2K3 R2) reports that the source file is being held with a read lock, even though no further operation is done with the file on the server. The lock is released once the application quits.</p>
  
  <p>We are able to reproduce the behaviour, even with the most basic code seen below :</p>
  
  <pre><code>static void Main(string[] args)
  {
      string sourceFile = @"\\win2K3server\resource\Production\IQE\sourceFolder\iqeconsole.exe";
      string destinationFile = @"d:\destinationFolder\iqeconsole.exe";
      System.IO.File.Copy(sourceFile,destinationFile,true);
  
      Console.ReadLine();
  }
  </code></pre>
  
  <p>The lock occurrs immediately during the <code>File.Copy()</code> line executing, and persists after this line has finished. In a more complex application, when the routine with the <code>File.Copy()</code> exits(but the application is still running), the lock persists.</p>
  
  <p>Only when the entire application is finished is the lock released.</p>
  
  <p>Changing <code>sourceFile</code> to use a mapped drive instead of a UNC path makes no difference to the behaviour.</p>
  
  <p>This behaviour does not happen when the source file is located on another server, or is located locally.</p>
  
  <p>If we add the following line after the <code>File.Copy</code>, the lock is released immediately :</p>
  
  <pre><code>new System.Security.Permissions.FileIOPermission(System.Security.Permissions.FileIOPermissionAccess.Read, new string[] { sourceFile }).Demand();
  </code></pre>
  
  <p>This all sounds to us as though there is something on the server that is causing this behaviour. We have ShadowProtect installed on the server along with McAfee anti-virus. Apart from that, it appears as though there is nothing else installed over-and-above Windows Server and its components.</p>
  
  <p>We are also not sure why Demanding a read permission on the file solves the problem.</p>
  
  <p>If you could answer these questions, we would appreciate it greatly:</p>
  
  <ol>
  <li>What is causing the file locks to persist?</li>
  <li>Why does Demanding a read permission solve the problem?</li>
  </ol>