c# -如何只授予当前用户访问权限,限制其他用户访问

本文关键字:用户 访问 权限 访问权 其他 | 更新日期: 2023-09-27 18:06:48

我想要一个应用程序创建一个文件夹,并限制当前和管理员以外的用户访问它。由于下面的代码,虽然当前用户也失去了访问权限,不能删除文件夹。

string rootPath = Environment.GetEnvironmentVariable("TEMP");
var rootDirectory = new DirectoryInfo(rootPath);
DirectoryInfo subFolder = rootDirectory.CreateSubdirectory("SubFolder");
var directorySecurity = subFolder.GetAccessControl();
var adminitrators = new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null);
directorySecurity.AddAccessRule(
    new FileSystemAccessRule(
        adminitrators,
        FileSystemRights.FullControl,
        InheritanceFlags.None,
        PropagationFlags.NoPropagateInherit,
        AccessControlType.Allow));
directorySecurity.AddAccessRule(
    new FileSystemAccessRule(
        WindowsIdentity.GetCurrent().Name,
        FileSystemRights.FullControl,
        InheritanceFlags.None,
        PropagationFlags.NoPropagateInherit, 
        AccessControlType.Allow));
var everyone = new SecurityIdentifier(WellKnownSidType.WorldSid, null);
directorySecurity.AddAccessRule(
    new FileSystemAccessRule(
        everyone,
        FileSystemRights.FullControl,
        InheritanceFlags.None,
        PropagationFlags.NoPropagateInherit,
        AccessControlType.Deny));
subFolder.SetAccessControl(directorySecurity);
subFolder.Delete(true); // <-- System.UnauthorizedAccessException

c# -如何只授予当前用户访问权限,限制其他用户访问

好的,那么完整的解决方案如下:

    正如@zerkms提议的,我们需要删除"拒绝所有人"。这就解决了系统问题。当前用户试图删除文件夹时抛出UnauthorizedAccessException。
  1. 正如这里所解释的,使用SetAccessRuleProtection来确保权限不会从父文件夹继承。

        string rootPath = Environment.GetEnvironmentVariable("TEMP");
        var rootDirectory = new DirectoryInfo(rootPath);
        DirectoryInfo subFolder = rootDirectory.CreateSubdirectory("SubFolder");
        var directorySecurity = subFolder.GetAccessControl();
        var adminitrators = new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null);
        directorySecurity.AddAccessRule(
            new FileSystemAccessRule(
                    adminitrators,
                    FileSystemRights.FullControl,
                    InheritanceFlags.None,
                    PropagationFlags.NoPropagateInherit,
                    AccessControlType.Allow));
        directorySecurity.AddAccessRule(
            new FileSystemAccessRule(
                    WindowsIdentity.GetCurrent().Name,
                    FileSystemRights.FullControl,
                    InheritanceFlags.None,
                    PropagationFlags.NoPropagateInherit, 
                    AccessControlType.Allow));
        directorySecurity.SetAccessRuleProtection(isProtected: true, preserveInheritance: false);
        subFolder.SetAccessControl(directorySecurity);
    

在这种情况下,显式的deny规则是多余的。

不允许的内容默认是拒绝的,所以只需删除最后一个deny for all规则,您就可以了。