Quantcast
Channel: Security
Viewing all articles
Browse latest Browse all 4737

AD current user username

$
0
0

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'.


Viewing all articles
Browse latest Browse all 4737


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>