首页 > 解决方案 > 使用 Windows 应用程序授予对文件夹的读取和写入权限

问题描述

我在 Installer.cs 文件中添加了以下代码,用于向设置文件添加一些功能。

代码是

public override void Install(IDictionary stateSaver)
    {
        // This gets the named parameters passed in from your custom action
        string folder = Context.Parameters["folder"];

        // This gets the "Authenticated Users" group, no matter what it's called
        SecurityIdentifier sid = new SecurityIdentifier(WellKnownSidType.AuthenticatedUserSid, null);

        // Create the rules
        FileSystemAccessRule writerule = new FileSystemAccessRule(sid, FileSystemRights.Write, AccessControlType.Allow);

        if (!string.IsNullOrEmpty(folder) && Directory.Exists(folder))
        {
            // Get your file's ACL
            DirectorySecurity fsecurity = Directory.GetAccessControl(folder);

            // Add the new rule to the ACL
            fsecurity.AddAccessRule(writerule);

            // Set the ACL back to the file
            Directory.SetAccessControl(folder, fsecurity);

        }
                    DirectoryInfo dInfo = new DirectoryInfo(folder);
        DirectorySecurity dSecurity = dInfo.GetAccessControl();
        dSecurity.AddAccessRule(new FileSystemAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), FileSystemRights.FullControl, InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit, PropagationFlags.NoPropagateInherit, AccessControlType.Allow));
        WindowsIdentity self = System.Security.Principal.WindowsIdentity.GetCurrent();
        dSecurity.AddAccessRule(new FileSystemAccessRule(self.Name,
        FileSystemRights.FullControl,
        InheritanceFlags.ObjectInherit |
        InheritanceFlags.ContainerInherit,
        PropagationFlags.None,
        AccessControlType.Allow));
        dInfo.SetAccessControl(dSecurity);
        base.Install(stateSaver);
    }

为了授予读写权限,我在上面添加了代码,它正在工作(如果我创建新的 Windows 应用程序并添加了此代码),但是当我使用安装文件时它不起作用

提前致谢

标签: c#windowssetup-project

解决方案


推荐阅读