如何以编程方式将此Active Directory作为LocalService访问?

时间:2017-08-01 17:03:30

标签: c# active-directory ldap windows-services

尝试从我的Windows服务访问本地ActiveDirectory。

我打算尝试使用LocalService来访问它,当我以管理员身份在Visual Studio中运行它时它会起作用,但是当我将它作为实际服务运行时它会失败。

我是否需要以某种方式向SecurityIdentifier提供DirectoryEntry?但它只需要usernamepassword而不是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);
}

它给了我 System.DirectoryServices.DirectoryServicesCOMException (0x80072030): There is no such object on the server.,我已尝试在LocalServiceNetworkService中运行该服务。

1 个答案:

答案 0 :(得分:1)

实际上,看起来我使用了错误的地址来访问ActiveDirectory。在我的本地机器上,我正在使用:

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

但我应该使用

Environment.UserDomainName

所以,如果域名不存在,我会采取后备方法......

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

现在连接到LDAP工作:

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

只是为了确认@Harry Johnston在另一个回复中所说的,使用NetworkService工作了! (我回到LocalService只是为了确定而且我失败了)