每当我调用此方法时,我都会崩溃。
public bool findSAMAccountByName(string environmentUserName)
{
try
{
const string Domain = "someserver";
// set up domain context
PrincipalContext ctx = new PrincipalContext(ContextType.Domain, Domain);
// find a user
UserPrincipal user = UserPrincipal.FindByIdentity(ctx, environmentUserName);
if (user != null)
{
// do something here....
string samAccountName = user.SamAccountName;
return true;
}
return false;
}
catch (Exception e)
{
e.ToString();
}
return false;
}
内部异常说
{“试图读取或写入受保护的内存。这通常表明其他内存已损坏。”}
StackTrace 是
at System.DirectoryServices.Interop.UnsafeNativeMethods.IAds.GetEx(String bstrName, Object& value)
at System.DirectoryServices.PropertyValueCollection.PopulateList()
at System.DirectoryServices.PropertyValueCollection..ctor(DirectoryEntry entry, String propertyName)
at System.DirectoryServices.PropertyCollection.get_Item(String propertyName)
at System.DirectoryServices.AccountManagement.PrincipalContext.DoLDAPDirectoryInitNoContainer()
at System.DirectoryServices.AccountManagement.PrincipalContext.DoDomainInit()
at System.DirectoryServices.AccountManagement.PrincipalContext.Initialize()
at System.DirectoryServices.AccountManagement.PrincipalContext.get_QueryCtx()
at System.DirectoryServices.AccountManagement.Principal.FindByIdentityWithTypeHelper(PrincipalContext context, Type principalType, Nullable`1 identityType, String identityValue, DateTime refDate)
at System.DirectoryServices.AccountManagement.Principal.FindByIdentityWithType(PrincipalContext context, Type principalType, String identityValue)
at System.DirectoryServices.AccountManagement.UserPrincipal.FindByIdentity(PrincipalContext context, String identityValue)
at ActiveRecord.MainWindow.findSAMAccountByName(String environmentUserName) in MainWindow.xaml.cs:line 60
at ActiveRecord.MainWindow..ctor() in MainWindow.xaml.cs:line 39
我对这个方法的调用导致了崩溃
if (findSAMAccountByName(Environment.UserName))
{
Console.WriteLine("Username found");
}
如果我删除/注释代码,它会编译并运行良好。
更新:听从 DJ KRAZE 的建议后
const string Domain = "someserver";
将 PrincipalContext 更改为接受 2 个参数后,新的 StackTrace 为
at System.Windows.Markup.WpfXamlLoader.Load(XamlReader xamlReader, IXamlObjectWriterFactory writerFactory, Boolean skipJournaledProperties, Object rootObject, XamlObjectWriterSettings settings, Uri baseUri)