删除所有目录权限

问题描述 投票:0回答:5

在 C# (2.0) 中,如何删除目录的所有权限,以便限制访问。 我将向有限的用户组重新添加访问权限。

c# .net security permissions
5个回答
25
投票

免责声明:我意识到这已经被回答并接受了,我真的很想将其发布为对已接受答案的评论,但是无法格式化评论迫使我将其发布为答案(其中,从技术上讲,是的)....

我想做同样的事情,并发现了你的问题。 Stu的回答帮助我想出了这个解决方案。 (请注意,我只对删除显式安全性感兴趣)。

private static DirectorySecurity RemoveExplicitSecurity(DirectorySecurity directorySecurity)
{
    AuthorizationRuleCollection rules = directorySecurity.GetAccessRules(true, false, typeof(System.Security.Principal.NTAccount));
    foreach (FileSystemAccessRule rule in rules)
        directorySecurity.RemoveAccessRule(rule);
    return directorySecurity;
}

这显然是这样使用的:

DirectoryInfo directoryInfo = new DirectoryInfo(path);
DirectorySecurity directorySecurity = directoryInfo.GetAccessControl();
directorySecurity = RemoveExplicitSecurity(directorySecurity);
Directory.SetAccessControl(path, directorySecurity);

8
投票

查看 System.Security.AccessControl 命名空间中的类,尤其是 DirectorySecurity.RemoveAccessRule 方法。

此外,如果您删除所有权限,那么您之后将无法添加任何权限:-)


3
投票

这里有一组来自 CodeProject 的有关 Windows ACL 编程的精彩文章:

Windows 访问控制模型

本系列的第 3 部分展示了 .NET 的具体方法。


2
投票

System.IO.Directory.GetAccessControl(),然后编辑返回的 FileSecurity 对象。


0
投票

模块工作得很好:

Imports System.IO
Imports System.Runtime.CompilerServices
Imports System.Security.AccessControl
Imports System.Security.Principal
Module Module1
    Sub Main()
        Dim folder = "your folder path"
        folder.CreateDirectory()
    End Sub
End Module
Module Extensions
    <Extension()>
    Public Sub CreateDirectory(path As String)
        Try
            If Not Directory.Exists(path) Then
                Dim fEveryone = New SecurityIdentifier(WellKnownSidType.WorldSid, Nothing)
                Dim fDirectorySecurity = New DirectorySecurity()
                Dim fFileSystemRights = FileSystemRights.FullControl
                Dim fInheritanceFlags = InheritanceFlags.ContainerInherit Or InheritanceFlags.ObjectInherit
                Dim fPropagationFlags = PropagationFlags.None
                Dim fAccessControlType = AccessControlType.Allow
                Dim fDirectoryAccessRule = New FileSystemAccessRule(fEveryone, fFileSystemRights, fInheritanceFlags, fPropagationFlags, fAccessControlType)
                fDirectorySecurity.AddAccessRule(fDirectoryAccessRule)
                Directory.CreateDirectory(path, fDirectorySecurity)
            End If
        Catch ex As PathTooLongException
            Debug.WriteLine("The path {0}; was too long.", path)
        Catch ex As UnauthorizedAccessException
            Debug.WriteLine("The path {0}; cannot be created because you do not have the rights to create it.", path)
        Catch ex As Exception
            Debug.WriteLine("Exception in {0} - {1}; {2}", ex.Source, ex, ex.Message)
        End Try
    End Sub
End Module


© www.soinside.com 2019 - 2024. All rights reserved.