Open a file without (really) locking it?

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()); } } 
+7
c # interop
source share
3 answers

If you work with the NTFS file system, you can create another hard link to the file in a temporary place, you can avoid the overhead of the file, and the first link should still be deleted (either the file itself or the directory) without executing the second.

+1
source share

The best solution I can come up with is to copy the file to a temporary scratch location. Then open the temporary file and delete it when I finish.

0
source share

FileOpen uses CreateFile in Kernel32.dll. I'm not sure that you can achieve anything more than what the .NET framework provides, since all the options are already there if you are not executing it as a deal .

0
source share

All Articles