Question

I am trying to get the user details from different domain but its throwing the following error:

An exception of type 'System.Runtime.InteropServices.COMException' occurred in System.DirectoryServices.dll but was not handled in user code

Code as as below:

// Getting domain
var context = new DirectoryContext(DirectoryContextType.Domain, "alpha");
Domain domain = Domain.GetDomain(context);

using (DirectorySearcher searcher = new DirectorySearcher())
{
    var de = new DirectoryEntry(domain.Name);
    searcher.SearchRoot = de;
    searcher.SearchScope = SearchScope.Subtree;
    searcher.PropertiesToLoad.Add("sAMAccountName");
    searcher.Filter = string.Format("(&(objectClass=user)(sAMAccountName={0}))", "myusername");

    // *** ERROR HERE ***        
    var results = searcher.FindAll();
}

I have already tried running visual studio as Domain Admin but no luck.

Thanks in advance.

Was it helpful?

Solution

Following code only works when you add name space using System.DirectoryServices.ActiveDirectory and also add a reference.

// Get user name
string userName = User.Identity.Name;
var domainName = username.Split('\\')[0];

// Getting domain
var directoryContext = new DirectoryContext(DirectoryContextType.Domain, domainName);
Domain domain = Domain.GetDomain(directoryContext);

using (PrincipalContext principalContext = new PrincipalContext(ContextType.Domain, domain.Name))
{
    using (UserPrincipal user = UserPrincipal.FindByIdentity(principalContext, userName))
    {
        if (user != null)
        {
            // Get details here
            var name = user.GivenName;
        }
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top