codenamezero
codenamezero

Reputation: 3079

How to programmatically access this Active Directory as LocalService?

Trying to access the local ActiveDirectory from my Windows Service.

I was going to try using the LocalService to access it, it works when I run it inside Visual Studio as Administrator, but failed when I run it as an actual Service.

Do I need to provide the SecurityIdentifier to DirectoryEntry somehow? But it only takes username and password and not SecurityIdentifier...

var fqhn = System.Net.Dns.GetHostEntry(Environment.MachineName).HostName;
using (DirectoryEntry root = new DirectoryEntry(string.Format("LDAP://{0}/RootDSE", fqhn)))
{ 
    string ctx = root.Properties["configurationNamingContext"].Value.ToString();
    string path = string.Format("LDAP://{0}/CN=Microsoft Exchange,CN=Services,{1}", 
                                fqhn, ctx);
    var blah = new DirectoryEntry(path);
}

It gives me System.DirectoryServices.DirectoryServicesCOMException (0x80072030): There is no such object on the server., I've tried running the service in both LocalService or NetworkService.

Upvotes: 0

Views: 1165

Answers (1)

codenamezero
codenamezero

Reputation: 3079

Actually, it looks like I was using the wrong address to access the ActiveDirectory. On my local machine, I was using:

System.Net.Dns.GetHostEntry(Environment.MachineName).HostName;

But I should be using the domain instead:

Environment.UserDomainName

So I kind of made a fallback approach in case the domain is not there...

string domain = Environment.UserDomainName;
if (String.IsNullOrEmpty(domain))
    domain = System.Net.Dns.GetHostEntry(Environment.MachineName).HostName;

Now connecting to the LDAP works:

new DirectoryEntry(string.Format("LDAP://{0}/RootDSE", domain)

And just to confirm what @Harry Johnston said in the other reply, using NetworkService worked! (I reverted back to LocalService just to be sure and it failed on me)

Upvotes: 1

Related Questions