title: How do I properly open a file for deletion?
body: <p>I thought this is a completely trivial task but it gave me some headache. I would like to open a file to ensure I got exclusive access, test for certain conditions, then delete it.</p>
  
  <p>Right now I'm using a 99% approach:</p>
  
  <pre><code>FileStream s = null;
  try {
      s = new FileStream (
          path,
          FileMode.Open,
          FileAccess.ReadWrite,
          FileShare.None);
      // some stuff about the file is checked here
      s.Dispose ();
      // hope the file is not accessed by someone else...
      File.Delete (path);
      return true;
  }
  catch (IOException) {
      if (s !=null) s.Dispose ();
      return false;
  }
  </code></pre>
  
  <p>This usually works, but I figured there'd be a better way that avoids the edge condition.</p>
  
  <p>Opening the file with a DeleteOnClose flag does not work because said check (which occurs after opening with the deletion flag already set) might indicate that the file should not be deleted.</p>