title: Lock file exclusively then delete/move it
body: <p>I'm implementing a class in C# that is supposed to monitor a directory, process the files as they are dropped then delete (or move) the processed file as soon as processing is complete. Since there can be multiple threads running this code, the first one that picks up the file, locks it exclusively, so no other threads will read the same file <strong>and no external process or user can access in any way</strong>. I would like to keep the lock until the file is deleted/moved, so there's no risk of another thread/process/user accessing it.</p>
  
  <p>So far, I tried 2 implementation options, but none of them works as I want.</p>
  
  <p><em>Option 1</em></p>
  
  <pre><code>FileStream fs = file.Open(FileMode.Open, FileAccess.Read, FileShare.Delete);
  //Read and process
  File.Delete(file.FullName); //Or File.Move, based on a flag
  fs.Close();
  </code></pre>
  
  <p><em>Option 2</em></p>
  
  <pre><code>FileStream fs = file.Open(FileMode.Open, FileAccess.Read, FileShare.None);
  //Read and process
  fs.Close();
  File.Delete(file.FullName); //Or File.Move, based on a flag
  </code></pre>
  
  <p>The issue with <em>Option 1</em> is that other processes can access the file (they can delete, move, rename) while it should be fully locked.</p>
  
  <p>The issue with <em>Option 2</em> is that the file is unlocked before being deleted, so other processes/threads can lock the file before the delete happens, so the delete will fail.</p>
  
  <p>I was looking for some API that can perform the delete using the file handle I already have exclusive access.</p>
  
  <p><em>Edit</em></p>
  
  <p>The directory being monitored resides in a pub share, so other users and processes have access to it.
  <strong>The issue is not managing the locks within my own process. The issue I'm trying to solve is how to lock a file exclusively then move/delete it without releasing the lock</strong></p>