简体   繁体   中英

How to lock a directory and prevent it from being deleted?

I need to check whether a directory exists, create it if it doesn't and lock it on the startup of my application. So as long as the application runs, no one can delete the directory.

I guess I can save a dumb file inside it and keep it open so it can't be deleted but I prefer not to if that is possible . How can I achieve that?


Right now, I do this whenever I need to write a file in it:

if (!Directory.Exists(path))
    Directory.CreateDirectory(path);

And even in this example, it's still possible to delete the directory between Directory.CreateDirectory and the File.Create calls.

Create a dummy temp file in the directory and keep it open for the life of the program. That way anyone attempting to delete the directory will get the "directory in use" error message and be unable to delete it.

I would suggest you to create a temporary folder somewhere and do all you processing there and once its completed create and move your files to the destination folder. You can delete your temp folder once every thing gets completed successfully.

Use CreateFile WINAPI function on dir. Not tested but I think it would work.

[DllImport("kernel32.dll", SetLastError = true)]
        private static extern SafeFileHandle CreateFile(
            string lpFileName,
            FileAccess dwDesiredAccess,
            FileShare dwShareMode,
            IntPtr lpSecurityAttributes,
            FileMode dwCreationDisposition,
            int dwFlagsAndAttributes,
            IntPtr hTemplateFile);

const int FILE_FLAG_BACKUP_SEMANTICS = 0x02000000;
var dirlock = CreateFile("C:\\mydir", FileAccess.Read, FileShare.None, IntPtr.Zero, FileMode.Open,
                                     FILE_FLAG_BACKUP_SEMANTICS, IntPtr.Zero);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM