使用Windows中的凭据创建/打开目录

时间:2013-10-22 03:57:22

标签: c# active-directory

我希望使用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;
    }

1 个答案:

答案 0 :(得分:1)

假设您正在处理一个简单的场景,您可能正在寻找Directory.CreateDirectory(字符串路径,DirectorySecurity directorySecurity),您可以找到该文档here

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