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