我编写了一个非常示例的测试程序,并将其作为本地系统帐户在域机器中运行。这是代码的样子:
static void Main(string[] args)
{
try
{
System.Console.Out.WriteLine("Test Start");
List<string> temp = new List<string>();
temp.Add(Environment.UserDomainName);
temp.Add("test");
temp.Add("test.com");
temp.Add("dc.test.com");
temp.Add("gc.test.com");
foreach (var i in temp)
{
using (HostingEnvironment.Impersonate())
{
System.Console.WriteLine("LDAP://{0}", i);
DirectoryEntry entry = new DirectoryEntry("LDAP://" + i);
try
{
entry.RefreshCache();
string nativeGuid = entry.NativeGuid;
string path = entry.Path;
string server = entry.Options.GetCurrentServerName();
System.Console.WriteLine("{0} success!", i);
}
catch (Exception e)
{
System.Console.WriteLine("{0}\n {1}", i, e);
}
}
}
System.Console.Out.WriteLine("Test End");
}
catch (Exception e)
{
System.Console.Out.WriteLine("e:Main{0}", e.Message);
}
System.Console.In.ReadLine();
}
域的 NetBIOS 名称是“test”,完整的域名是“test.com”。“dc.test.com”是 DC FQDN,“gc.test.com”是 GC FQDN。
它适用于“test.com”、“dc.test.com”和“gc.test.com”,但它会为“test”和“Environment.UserDomainName”抛出 DirectoryServicesCOMException (0x80072020)。
详细运行结果为:
Test Start
LDAP://TEST
TEST
System.DirectoryServices.DirectoryServicesCOMException (0x80072020): An operati
ons error occurred.
at System.DirectoryServices.DirectoryEntry.Bind(Boolean throwIfFail)
at System.DirectoryServices.DirectoryEntry.Bind()
at System.DirectoryServices.DirectoryEntry.RefreshCache()
at ConsoleApplication1.Program.Main(String[] args)
LDAP://test
test
System.DirectoryServices.DirectoryServicesCOMException (0x80072020): An operati
ons error occurred.
at System.DirectoryServices.DirectoryEntry.Bind(Boolean throwIfFail)
at System.DirectoryServices.DirectoryEntry.Bind()
at System.DirectoryServices.DirectoryEntry.RefreshCache()
at ConsoleApplication1.Program.Main(String[] args)
LDAP://test.com
test.com success!
LDAP://dc.test.com
dc.test.com success!
LDAP://gc.test.com
gc.test.com success!
Test End
如果我以 domian admin 帐户运行它,一切正常。知道是什么原因造成的吗?十分感谢!