Prevent a user from deleting, moving or renaming a file

十年热恋 提交于 2019-11-30 18:25:11

When you are opening the file, you can specify the sharing mode.

Opening the file with FileAccess.Read gives you the ability to read the file, while FileShare.ReadWrite allows the file to continue to be edited, but not deleted or moved.

var fs = File.Open(@"C:\temp\file.txt", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
MessageBox.Show("File Locked");  // While the messagebox is up, try to open or delete the file.
// Do your work here
fs.Close();

This will prevent moving or deleting the file but allows read and write:

    using (FileStream fs = new FileStream(@"C:\TestDir\Test.txt", FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
    {
        // Do Stuff.
    }

FileStream.Lock is actually a range lock which prevents modification of a particular portion of a file while the lock is held.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!