I am developing a window service application, i have the below code in C# to get the active directory username of the current user
public string GetUserID()
{
using (var domainContext = new PrincipalContext(ContextType.Domain, "IPaddress", "username", "password"))
{
UserPrincipal user = UserPrincipal.Current;
if (user != null)
{
userid = user.SamAccountName; // or whatever you mean by "login name"
}
}
return userid;
}
The above code worked well in a console application but when used it in a window service application i got the below error
Unable to cast object of type 'System.DirectoryServices.AccountManagement.GroupPrincipal' to type 'System.DirectoryServices.AccountManagement.UserPrincipal'.