我有一些C#代碼試圖使用提供的計算機名進行LDAP搜索,以確定計算機帳戶是否被禁用。大部分代碼取自this SO question。如果我禁用AD中的帳戶並且在活動的計算機上爲false,示例鏈接中的代碼工作良好並且正確顯示爲true。問題是我不能按照它最初提供的方式完全使用代碼,它必須以我在下面粘貼它的方式使用。下面的代碼的問題是它總是返回false,它傳遞給它的計算機名稱似乎並不重要。我也意識到,foreach循環可能不需要,因爲我只是想找到一臺計算機。C#布爾沒有正確設置
using System;
using System.DirectoryServices;
namespace DynamicNamespace
{
public class DynamicClass
{
public System.Boolean DynamicMethod(System.Boolean IsDisabled, System.String ComputerName)
{
//the string should be your a DC(domain controller)
const string ldap = "LDAP://server-name";
//DirectoryEntry is used for manipulating objects (users, computers)
DirectoryEntry entry = new DirectoryEntry(ldap);
//DirectorySearcher responds to a filter method for LDAP searches
//http://www.tek-tips.com/faqs.cfm?fid=5667 has a decent query guide
DirectorySearcher dSearch = new DirectorySearcher(entry);
//SAM Account Name was showing a $ sign at one point, using * for wildcard
dSearch.Filter = String.Format("samAccountName={0}*", ComputerName);
dSearch.PropertiesToLoad.Add("samAccountName");
dSearch.PropertiesToLoad.Add("userAccountControl");
SearchResultCollection results = dSearch.FindAll();
foreach (SearchResult result in results)
{
int userAccountControl = Convert.ToInt32(result.Properties["userAccountControl"][0]);
string samAccountName = Convert.ToString(result.Properties["samAccountName"][0]);
bool disabled = ((userAccountControl & 2) > 0);
if (disabled == false)
{
IsDisabled = false;
}
else
{
IsDisabled = true;
}
}
return IsDisabled;
}
}
}
您獲得'結果'有多少結果?爲什麼你不能只使用IsDisabled =((userAccountControl&2)> 0); ? – RQDQ 2011-04-08 15:54:03
你的問題是什麼? – Jason 2011-04-08 15:55:40
爲什麼你將IsDisabled作爲參數傳遞,如果你正在更新值並返回它?爲什麼不在本地範圍內聲明它? – Infotekka 2011-04-08 16:00:28