How to programmatically access this Active Directory as LocalService?

0

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.

c#
active-directory
ldap
windows-services
asked on Stack Overflow Aug 1, 2017 by codenamezero • edited Aug 1, 2017 by codenamezero

1 Answer

1

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)

answered on Stack Overflow Aug 2, 2017 by codenamezero

User contributions licensed under CC BY-SA 3.0