title: Open file without (really) locking it?
body: <p>Is it possible to open a file in a way that allows subsequent deletion/renaming of its parent folder?</p>
  
  <p>I know you can do this:</p>
  
  <pre><code>File.Open("foo.bar", FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete)
  </code></pre>
  
  <p>Which will allow for the file to be deleted when the file handle is closed.  However, if it does not allow the parent folder to be deleted without error.</p>
  
  <p>I couldn't find anything in the framework.  Have I overlooked something, or is there a native API I can interop to.</p>
  
  <p>Note: I don't care if I get an exception when using the stream of the deleted file.  In fact that would be ideal.</p>
  
  <p><strong>UPDATE:</strong></p>
  
  <p>So the most promising idea was the <a href="https://stackoverflow.com/questions/648939/open-file-without-really-locking-it/649372#649372">Hardlink</a>, however I just can't make it work.  I still end up with Access Denied when i try to delete the parent directory.  Here is my code:</p>
  
  <pre><code>class Program
  {
      [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
      static extern bool CreateHardLink(string lpFileName, string lpExistingFileName, IntPtr lpSecurityAttributes);
  
      static void Main(string[] args)
      {
          string hardLinkPath = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
          string realPath = @"C:\foo\bar.txt";
          if (CreateHardLink(hardLinkPath, realPath, IntPtr.Zero))
          {
              using (FileStream stream = File.Open(hardLinkPath, FileMode.Open, FileAccess.Read, FileShare.Delete | FileShare.ReadWrite))
              {
                  Console.Write("File locked");
                  Console.ReadLine();
              }
  
              File.Delete(hardLinkPath);
          }
          else
              Console.WriteLine("LastError:{0}", Marshal.GetLastWin32Error());
      }
  }
  </code></pre>