-1

我想使用 Active Directory 用户凭据创建目录,只有该用户有权访问目录操作,例如打开列表文件、读取文件等。

 public void CreateDirectory(int value)
    {
        string drive = Directory.GetDirectoryRoot(HostingEnvironment.ApplicationPhysicalPath);
        string path = "D://" + "4524l";
        DirectoryInfo dinfo = Directory.CreateDirectory(path);

        string domainAndUsername = "456456.com" + @"\" + "guserone";
        DirectoryEntry entry = new DirectoryEntry("LDAP://124.com", domainAndUsername, "a55in123*");


        //Bind to the native AdsObject to force authentication.
        object obj = entry.NativeObject;

        DirectorySearcher search = new DirectorySearcher(entry);

        search.Filter = "(SAMAccountName=" + "guserone" + ")";
        search.PropertiesToLoad.Add("cn");
        SearchResult result = search.FindOne();   

        DirectorySecurity myDirectorySecurity = dinfo.GetAccessControl();
        //myDirectorySecurity.SetOwner(newUser);
        myDirectorySecurity = RemoveExplicitSecurity(myDirectorySecurity);
        dinfo.SetAccessControl(myDirectorySecurity);
        myDirectorySecurity.AddAccessRule(new FileSystemAccessRule(domainAndUsername,
                                         FileSystemRights.FullControl, AccessControlType.Allow));
        dinfo.SetAccessControl(myDirectorySecurity);
        myDirectorySecurity.SetAccessRuleProtection(true, false);
    }

    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;
    }
4

1 回答 1

1

假设您正在处理一个简单的场景,您可能正在寻找 Directory.CreateDirectory(string path, DirectorySecurity directorySecurity),您可以在此处找到文档。

那里有一个不错的示例,其中包括创建基本访问控制。

于 2013-10-22T04:11:01.183 回答