首页 > 解决方案 > C# .Net FileSystemRights 拒绝删除权限并稍后添加

问题描述

我的程序生成一个文件。这个文件应该受到保护,这样用户就不会意外删除它。因此,它需要以某种方式加以保护。

由于文件应该受到保护,而应用程序关闭时 FileStream.Lock不是此任务的合适解决方案。

我试图在文件上拒绝 FileSystemRights.Delete,例如:

    fSecurity.AddAccessRule(new FileSystemAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null),
                FileSystemRights.Delete, AccessControlType.Deny));

但这并不能阻止删除,为此我必须像这样更改它:

    fSecurity.AddAccessRule(new FileSystemAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null),
                FileSystemRights.Delete | FileSystemRights.WriteAttributes, AccessControlType.Deny));

(用户可以打开文件属性并添加回 WriteAttribute 权限,然后可以删除文件,这很好)

现在的问题是:该文件应该可以从应用程序中删除。但是做:

    fSecurity.RemoveAccessRule(new FileSystemAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null),
                FileSystemRights.Delete | FileSystemRights.WriteAttributes, AccessControlType.Deny));
    // or:
    fSecurity.AddAccessRule(new FileSystemAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null),
                FileSystemRights.Delete | FileSystemRights.WriteAttributes, AccessControlType.Allow));

导致 UnauthorizedAccessException。所以我不能撤销我所做的。这很奇怪,因为在文件资源管理器中它绝对有可能这样做。


所以我的问题是 -您如何再次授予删除权限-或者:保护文件以防意外删除的最佳方法是什么



该文件已在 %appdata% 中,但由于用户可能会删除其他文件夹,因此绝对不能意外删除此文件

标签: c#.netfile-security

解决方案


@canton7 谢谢!这非常有帮助

好的,经过反复试验,我得到了解决方案:

  1. 您必须将文件设置为只读。单独拒绝删除不起作用
  2. 您必须拒绝删除 + WriteAttributes - 如果您不这样做,可以在文件资源管理器中删除文件而无需请求权限。

  3. 再次解锁文件时:加回权限

    • 你必须删除你添加的拒绝规则
    • 并且您必须添加标志以允许
    • 只做其中一项是行不通的
  4. 删除只读标志
        private static void LockFile(string _FullPath)
        {
            File.SetAttributes(_FullPath, File.GetAttributes(_FullPath) | FileAttributes.ReadOnly);

            FileSecurity fSecurity = File.GetAccessControl(_FullPath);

            fSecurity.AddAccessRule(new FileSystemAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null),
                FileSystemRights.Delete | FileSystemRights.WriteAttributes, AccessControlType.Deny));

            File.SetAccessControl(_FullPath, fSecurity);
        }

        private static void UnLockFile(string _FullPath)
        {
            FileSecurity fSecurity = File.GetAccessControl(_FullPath);

            fSecurity.AddAccessRule(new FileSystemAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null),
                FileSystemRights.Delete | FileSystemRights.WriteAttributes, AccessControlType.Allow));

            fSecurity.RemoveAccessRule(new FileSystemAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null),
                FileSystemRights.Delete | FileSystemRights.WriteAttributes, AccessControlType.Deny));

            File.SetAccessControl(_FullPath, fSecurity);

            File.SetAttributes(_FullPath, FileAttributes.Normal);
        }

推荐阅读