using(PrincipalContext oPrincipalContext = new PrincipalContext(ContextType.Machine, computer.Name, null, ContextOptions.Negotiate, Settings.UserName, Settings.UserPassword))
using(GroupPrincipal oGroupPrincipal = GroupPrincipal.FindByIdentity(oPrincipalContext, Settings.AdministratorsGroup))
{
// perform operations here
}
更改您的代码并将其包装在using语句中,否则您在尝试调用 Dispose() 方法时可能会遇到一些错误,原因是您尝试处理连接时可能已经关闭。
如果您使用 ActiveDirectory,您可以在此处使用此代码并尝试任一示例
示例 1
如果您使用 .NET 3.5,则可以使用 System.DirectoryServices.AccountManagement 命名空间并轻松验证您的凭据:
// create a "principal context" - e.g. your domain (could be machine, too)
using(PrincipalContext pc = new PrincipalContext(ContextType.Domain, "YOURDOMAIN"))
{
// validate the credentials
bool isValid = pc.ValidateCredentials("myuser", "mypassword");
}
示例 2
using System.Security;
using System.DirectoryServices.AccountManagement;
public struct Credentials
{
public string Username;
public string Password;
}
public class Domain_Authentication
{
public Credentials Credentials;
public string Domain;
public Domain_Authentication(string Username, string Password, string SDomain)
{
Credentials.Username = Username;
Credentials.Password = Password;
Domain = SDomain;
}
public bool IsValid()
{
using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, Domain))
{
// validate the credentials
return pc.ValidateCredentials(Credentials.Username, Credentials.Password);
}
}
}
上面的公共 bool IsValid() 方法应该适用于您要查找的内容。
看看 PrincipalContext.ValidateCredentials
对于您的 FindByIdentity 部分,您可以尝试以下替换代码
string strName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
// This is here because of a .Net error that gets 0x80005000 on "isUser = user.IsMemberOf(groupU);"
string domainName = strName.Split('\\')[0];
var pc = new PrincipalContext(ContextType.Domain, domainName);
附加参考链接 StackOverFlow Post
ContextType.Machine