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());
}
}
Right-click a file (or click the ellipses (...)) to open the More Options menu. Click Lock. Choose a duration for the lock. If you choose unlimited, the file will be locked until you unlock it manually.
Windows locks certain types of files to prevent them from being modified simultaneously by two different users or two different applications. Normally, a file lock is engaged when the file is open, and Windows releases the lock when the application associated with the file is closed.
File locking is a data management feature that restricts other users from changing a specific file. This allows only one user or process access to this file at any given time. This is to prevent the problem of interceding updates on the same files.
If you're working with an NTFS you can create another hardlink to the file in a temporary location, you'll avoid the file copy overhead, and the first link should still be deletable (either the file itself or a containing directory) without effecting the second.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With