Skip to main content
 首页 » 编程设计

c#之来自 C# 的 Active Directory 查找在服务器上失败但在本地工作

2024年02月24日19birdshome

在我的工作场所,我必须处理 2 个不同的域 x.com(父目录)及其子域 y.x.com

父域 (x.com) 拥有所有事件目录用户、计算机等。从我位于 x.com 域中的本地工作站,我可以很好地阅读事件目录用户的电子邮件。

服务器位于域 y.x.com 中,它是 x 的子域。在服务器上,事件目录读取失败,并且未从事件目录中读取电子邮件地址。

除此之外,我还尝试从位于 y.x.com 域(与服务器相同)的虚拟机中使用相同的代码,令我惊讶的是这成功了。

我在 .NET 中使用目录服务来执行此操作,我的代码如下:

string userEmail = string.Empty; 
 
try 
{ 
 accountName = accountName.Replace(ConfigurationManager.AppSettings["DomainName"].ToString(), ""); 
 
 DirectorySearcher ds = new DirectorySearcher() 
 { 
  SearchRoot = new DirectoryEntry() 
  { 
   Path = ConfigurationManager.AppSettings["DirectoryPath"].ToString(), 
   AuthenticationType = AuthenticationTypes.Secure 
  } 
 }; 
 
 ds.Filter = "(SAMAccountName=" + accountName + ")"; 
 ds.PropertiesToLoad.Add(ConfigurationManager.AppSettings["ADMailPropertyName"].ToString()); 
 
 SearchResult result = ds.FindOne(); 
 
 if (result != null) 
 { 
  userEmail = result.Properties[ConfigurationManager.AppSettings["ADMailPropertyName"].ToString()][0].ToString(); 
 } 
} 
catch (Exception e) 
{ 
 //Log error 
} 
 
return userEmail; 

如有任何帮助,我们将不胜感激。

请您参考如下方法:

您的程序在服务器上运行的用户帐户是否具有访问 Active Directory 的必要权限?