title: Open, Lock, Truncate and Write to a file
body: <p>I'm trying to replicate Excel's behaviour when opening and editing files, that is:</p>
  
  <ul>
  <li>File is opened and locked for exclusive write access</li>
  <li>Other users are allowed to read the file</li>
  </ul>
  
  <p>I'm using the following code to open the file, read and prepare for later writing:</p>
  
  <pre><code>_fileStream = new FileStream(filePath, FileMode.Open, FileAccess.ReadWrite, FileShare.Read);
  _fileReader = new StreamReader(_fileStream);
  _fileWriter = new StreamWriter(_fileStream);
  var contents = _fileReader.ReadToEnd();
  </code></pre>
  
  <p>(In a class that implements IDisposable and disposes the streams)</p>
  
  <p>It apparently works fine aside from one issue when I later save using the following code:</p>
  
  <pre><code>_fileWriter.BaseStream.Seek(0, SeekOrigin.Begin);
  _fileWriter.Write(content);
  _fileWriter.Flush();
  </code></pre>
  
  <p>The problem is that I need to truncate the file before saving, and the above only overwrites. If the new content is shorter than what was loaded, I end up with a bad file due to partial old content.</p>
  
  <p>How do I truncate a filestream before writing (but not before reading)?</p>
  
  <p>Is there perhaps a better way to gain exclusive access to the file than what I am doing?</p>