Reputation: 1237
I have a method that returns the list for the users and trying to get the fullname based on the domainid. So that i want to populate this list to the Dropdown.
The below code works fine in the local and is throwing exception on the DevBox that "object reference not set ..." at the below line.
UserPrincipal.FindByIdentity(new PrincipalContext(ContextType.Domain), stringArray[x]).Name;
Anyone has any solution?
public static List<SelectListItem> GetUsers()
{
try
{
//Get Users list
string usersList = “nraja01,sdaniel01,mmontgo01”;
char[] charArray = new char[] { ',' };
string[] stringArray = usersList.Split(charArray);
List<SelectListItem> users = new List<SelectListItem>();
var user = new SelectListItem();
//loop through each user
for (int x = 0; x <= stringArray.GetUpperBound(0); x++)
{
user = new SelectListItem();
user.Value = stringArray[x];
user.Text = UserPrincipal.FindByIdentity(new PrincipalContext(ContextType.Domain), stringArray[x]).Name;
users.Add(user);
}
return users;
}
catch (Exception ex)
{
_log.Error("Error occured in GetUsers() method: ", ex);
return null;
}
}
Upvotes: 0
Views: 1480
Reputation: 5403
I've managed to retrieve the users full-name by using this.
System.DirectoryServices.AccountManagement.UserPrincipal.Current.GivenName
Upvotes: 0
Reputation: 4851
Because of a bug in .NET 4.0, you have to use a different constructor for the PrincipalContext when you are using ContextType.Domain. Use this constructor:
PrincipalContext(ContextType, string)
For example:
PrincipalContext principalContext = new PrincipalContext(ContextType.Domain, Environment.UserDomainName)
See these links for details on the bug:
Upvotes: 1