Is it possible to open a file in a way that allows subsequent deletion/renaming of its parent folder?
I know you can do this:
File.Open("foo.bar", FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete)
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.
I couldn't find anything in the framework. Have I overlooked something, or is there a native API I can interop to.
Note: I don't care if I get an exception when using the stream of the deleted file. In fact that would be ideal.
UPDATE:
So the most promising idea was the Hardlink, 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:
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());
}
}