如何授予文件权限而不是目录权限

时间:2019-03-26 05:16:32

标签: c# acl

我正在使用以下代码授予目录权限

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)下的文件,该怎么做?

2 个答案:

答案 0 :(得分: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);

    }

答案 1 :(得分: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);