I'm开发者_如何学JAVA stumped..
I'm trying to get the userPrincipalName from AD as follows:
DirectorySearcher search = new DirectorySearcher("LDAP://DCHS");
search.Filter = String.Format("(SAMAccountName={0})", UserName);
SearchResult result = search.FindOne();
DirectoryEntry entry = result.GetDirectoryEntry();
_UPN = entry.Properties["userPrincipalName"][0].ToString();
But this gives me:
Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
Can anyone tell me why this is happening?
EDIT: This code gets the SSID of the current user. I need to make this work on any user I enter into a text box.
WindowsIdentity windowsId = new WindowsIdentity(WindowsIdentity.GetCurrent().Token);
_SSID = windowsId.User.ToString()
I believe the issue is because you are treating the userPrincipalName entry as an array of values. Try modifying your code as follows:
DirectorySearcher search = new DirectorySearcher("LDAP://DCHS");
search.Filter = String.Format("(SAMAccountName={0})", UserName);
SearchResult result = search.FindOne();
DirectoryEntry entry = result.GetDirectoryEntry();
_UPN = entry.Properties["userPrincipalName"].Value.ToString();
Notice that I changed the last line from [0] to Value. That should fix your issue.
The one thing I would say is that I would do some checking before trying to read this value. There are cases where a user wouldn't have a UPN. In that case, the code would throw an error when you tried to access the field (the field wouldn't exist so it wouldn't be that you just need to make sure it isn't null).
If you're on .NET 3.5 and up, you should check out the System.DirectoryServices.AccountManagement
(S.DS.AM) namespace. Read all about it here:
Managing Directory Security Principals in the .NET Framework 3.5
Basically, you can define a domain context and easily find users and/or groups in AD:
// set up domain context
PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
// find user by name
UserPrincipal user = UserPrincipal.FindByIdentity(UserName);
if(user != null)
{
string upn = user.UserPrincipalName;
}
The new S.DS.AM makes it really easy to play around with users and groups in AD:
The obvious thing to do to avoid the exception (if that's valid) is to do
if (entry.Properties["userPrincipalName"].Count > 0)
{
_UPN = entry.Properties["userPrincipalName"][0].ToString();
}
but if you were supposed to get a valid result and you aren't then I would check the LDAP connection string and such. There are a few LDAP browsers that you could use (commercial + trial) to get your connection string right.
精彩评论