2012-02-13 124 views
0

我有在Active Directory返回用户名的Intranet应用的功能:从mycompany.com更改我的域名

public string GetCurrentUsersName() 
    { 
     //Get the username and domain information 
     string user = Environment.UserName; 
     string domainName = Environment.UserDomainName; 

     //Set the correct format for the AD query and filter 
     string ldapQueryFormat = @"LDAP://" + domainName + ".com/DC=" + domainName + ",DC=com"; 
     string queryFilterFormat = @"(&(samAccountName=" + user + ")(objectCategory=person)(objectClass=user))"; 

     SearchResult result = null; 
     using (DirectoryEntry root = new DirectoryEntry(ldapQueryFormat)) 
     { 
      using (DirectorySearcher searcher = new DirectorySearcher(root)) 
      { 
       searcher.Filter = queryFilterFormat; 
       SearchResultCollection results = searcher.FindAll(); 

       result = (results.Count != 0) ? results[0] : null; 
      } 
     } 

     //Get the email property from AD 
     string name = result.Properties["displayName"][0] as string; 
     return name; 
    } 

我最近更改了域名mycompany.local。每当我尝试运行此方法时,我现在都会收到一个错误,我应该更改某些内容吗?字符串domainName用于等于mycompany,但现在它等于myco,因为这是我使用的域名。

我收到的错误是:

System.Runtime.InteropServices.COMException:服务器不可操作。

回答

1

如果您最近更改域从mycompany.com到mycompany.local为AD查询正确的格式和过滤器应该是这样的:

//Set the correct format for the AD query and filter 
string ldapQueryFormat = @"LDAP://" + domainName + ".local/DC=" + domainName + ",DC=local"; 

与“局部”

+0

你”更换“COM”这个工作正常,但是由于我的服务器仍旧在旧域中,所以出现了一个双跳问题,所以我不得不使用下面的代码:using(HostingEnvironment.Impersonate()) {//我的代码} – CallumVass 2012-02-14 08:07:17

0

是否有理由动态构建域字符串?对于不同的用户或情况会有所不同吗?如果没有,为什么不把它定义为配置设置?您可以从Active Directory获取您的域的LDAP地址,然后您只需在网站的web.config文件中设置一个静态设置即可。域名的变化很少,因此设置比设法动态构建更容易。