title: Close/Dispose on FileStream
body: <p>I've got a bit of code in a product I am supporting that copies files:</p>
  
  <pre><code>using(System.IO.FileStream sourceFS = new System.IO.FileStream(sourcePath, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read))
              {
                  using(System.IO.FileStream targetFS = new System.IO.FileStream(targetPath, System.IO.FileMode.Create, System.IO.FileAccess.Write, System.IO.FileShare.Read))
                  {
                      while((read = sourceFS.Read(buffer, 0, buffer.Length)) &gt; 0)
                      {
                          targetFS.Write(buffer, 0, read);
                      }
  
                      targetFS.Flush();
                      targetFS.Close();
                  }
  
                  sourceFS.Close();
              }
  </code></pre>
  
  <p>Unfortunately, the users are reporting an exception informing us that the destination file is in use by another process. I've asked if there is a chance that someone has the file open (it's an Excel file) - apparently not...</p>
  
  <p>So, I put the thinking cap on... Is it possible we are leaving the destination file with a file lock against it? The only way I can see for targetFS not to be closed would be require both:</p>
  
  <ol>
  <li>An exception to be thrown within the inner using block, and </li>
  <li>The Dispose method not to actually close the stream.</li>
  </ol>
  
  <p>This sounded unlikely to me, but ever curious I used dotPeek from JetBrains to disassemble the Dispose method on the FileStream class - which doesn't seem to do all that much really - I'm guessing its "close" behaviour is provided by disposing of the handle...</p>
  
  <p>In essence though - the question is this - can anyone spot how this might be leaving a file with a lock against it?</p>