如何授予文件而不是目录

问题描述 投票:1回答:2

我正在使用下面的代码来授予目录权限

static void SetPermission(string path)
    {
        if (Directory.Exists(path))
        {
            var directoryInfo = new DirectoryInfo(path);

            // get the ACL of the directory
            var directorySecurity = directoryInfo.GetAccessControl();

            // remove inheritance, copying all entries so that they are direct ACEs
            directorySecurity.SetAccessRuleProtection(true, true);

            // do the operation on the directory
            directoryInfo.SetAccessControl(directorySecurity);

            // re-read the ACL
            directorySecurity = directoryInfo.GetAccessControl();

            // get the well known SID for "Users"
            var sid = new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null);

            // loop through every ACE in the ACL
            foreach (FileSystemAccessRule rule in directorySecurity.GetAccessRules(true, false, typeof(SecurityIdentifier)))
            {
                // if the current entry is one with the identity of "Users", remove it
                if (rule.IdentityReference == sid)
                    directorySecurity.RemoveAccessRule(rule);
            }

            var ntVirtaulUserName = @"NT Service\ServiceName";

            // Add the FileSystemAccessRule to the security settings. give full control for user 'NT Service\ServiceName' 
            directorySecurity.AddAccessRule(new FileSystemAccessRule(ntVirtaulUserName.Replace(@".\", ""), FileSystemRights.FullControl, AccessControlType.Allow));

            // do the operation on the directory
            directoryInfo.SetAccessControl(directorySecurity);
        }
    }

授予目录(Test)权限时,这是有效的,

SetPermission(@"C:\Test");

现在我想在Test目录(log.txt)下给一个文件许可,怎么做?

c# acl
2个回答
2
投票

您可以使用FileInfo类来处理文件的权限。它的用法就像DirectoryInfoHere是Microsoft文档。

    public static void AddFileSecurity(string FileName, string Account, FileSystemRights Rights, AccessControlType ControlType)
    {

        FileInfo fInfo = new FileInfo(FileName);
        FileSecurity fSecurity = fInfo.GetAccessControl();

        fSecurity.AddAccessRule(newFileSystemAccessRule(Account,Rights,ControlType));
        fInfo.SetAccessControl(fSecurity);

    }

0
投票

下面的代码是好的吗?

 var ntVirtaulUserName = @"NT Service\ServiceName";

            // Get a FileSecurity object that represents the
            // current security settings.
            FileSecurity fSecurity = File.GetAccessControl(@"C:\Test\log.txt");

            // Add the FileSystemAccessRule to the security settings.
            fSecurity.AddAccessRule(new FileSystemAccessRule(ntVirtaulUserName.Replace(@".\", ""), FileSystemRights.FullControl, AccessControlType.Allow));

            // Set the new access settings.
            File.SetAccessControl(@"C:\Test\log.txt", fSecurity);
© www.soinside.com 2019 - 2024. All rights reserved.