Is it possible to open the file in a way that allows you to subsequently delete / rename its parent folder?
I know you can do this:
File.Open("foo.bar", FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete)
This will delete the file when the file descriptor is closed. However, if this does not allow you to delete the parent folder without errors.
I could not find anything in the framework. I missed something, or is there my own API with which I can interact.
Note. I don't care if I get an exception when using a remote file stream. Actually, that would be perfect.
UPDATE:
Thus, Hardlink was the most promising idea, however I just can't get it to work. I am still gaining access 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()); } }
Greg dean
source share