[英]C# - Error listing all user accounts within Active Directory
我正在嘗試使用 Windows 表單列出 Active Directory 中所有基於用戶的帳戶的一些基本詳細信息(帶有基於帳戶是否啟用/禁用的自定義圖標)。 運行時,我收到此初始錯誤,並留下第二個屏幕截圖:
出於某種原因,該圖標位於第一列而不是第四列,我最終只有一個帳戶。 我的代碼:
try
{
var domainName = System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties().DomainName;
MessageBox.Show(domainName);
using (var context = new PrincipalContext(ContextType.Domain, domainName))
{
using (var searcher = new PrincipalSearcher(new UserPrincipal(context)))
{
foreach (var result in searcher.FindAll())
{
ListViewItem tmpItem = null;
DirectoryEntry child = result.GetUnderlyingObject() as DirectoryEntry;
switch (child.SchemaClassName)
{
case "user":
int flag = (int)child.Properties["userAccountControl"].Value;
bool disabled = Convert.ToBoolean(flag & 0x0002);
if (disabled == false)
{
tmpItem = new ListViewItem(new string[] {
(string)child.Properties["givenName"].Value,
(string)child.Properties["sn"].Value,
(string)child.Properties["samAccountName"].Value
}, (int)AdImages.User);
this.listView_ad.Items.Add(tmpItem);
}
else
{
tmpItem = new ListViewItem(new string[] {
(string)child.Properties["givenName"].Value,
(string)child.Properties["sn"].Value,
(string)child.Properties["samAccountName"].Value
}, (int)AdImages.block);
this.listView_ad.Items.Add(tmpItem);
}
break;
case "organizationalUnit":
break;
case "container":
break;
case "computer":
break;
case "group":
break;
default:
break;
}
}
}
}
}
catch (Exception e)
{
MessageBox.Show("ERROR : " + e, "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
編輯:刪除 try / catch 以獲得完整錯誤:
************** Exception Text **************
System.NullReferenceException: Object reference not set to an instance of an object.
at ComputeamPasswordManager.PasswordManager.getUsers()
at ComputeamPasswordManager.PasswordManager.PasswordManager_Load(Object sender, EventArgs e)
at System.Windows.Forms.Form.OnLoad(EventArgs e)
at System.Windows.Forms.Form.OnCreateControl()
at System.Windows.Forms.Control.CreateControl(Boolean fIgnoreVisible)
at System.Windows.Forms.Control.CreateControl()
at System.Windows.Forms.Control.WmShowWindow(Message& m)
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.ScrollableControl.WndProc(Message& m)
at System.Windows.Forms.Form.WmShowWindow(Message& m)
at System.Windows.Forms.Form.WndProc(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
編輯 2:在域設備上運行的 Visual Studio 的屏幕截圖...
嘗試改變這個(和類似的表達):
(string)child.Properties["givenName"].Value
像這樣:
(string)child.Properties["givenName"]?.Value ?? ""
我需要做的就是以管理員身份運行 Visual Studio!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.