C#测试为null

Ste*_*enL 3 c# active-directory

我正在使用C#编写一个简单的程序来读取Active Directory并显示Windows窗体程序中AD字段中保存的值.

如果某个属性不存在则程序崩溃,下面是我的代码,如何在不对每个属性执行try/catch的情况下捕获并转移到下一个字段?

DirectoryEntry usr = new DirectoryEntry("LDAP://" + domain, username, password);
DirectorySearcher searcher = new DirectorySearcher(usr);
searcher.Filter = "(sAMAccountName=" + GlobalClass.strUserName + ")";
searcher.CacheResults = false;
searcher.SearchScope = SearchScope.Subtree;
searcher.PropertiesToLoad.Add("givenName");
searcher.PropertiesToLoad.Add("telephoneNumber");

//program crashes here if telephoneNumber attribute doesn't exist.
textBoxFirstName.Text = usr.Properties["telephoneNumber"].Value.ToString();
Run Code Online (Sandbox Code Playgroud)

djd*_*d87 8

只是检查usr.Properties["telephoneNumber"]不起作用.您必须检查实际值.错误是发生的原因是因为你打电话ToString()Value是空.

user.PropertiesPropertyValueCollection无论输入到集合索引器中的属性名称如何,都将始终返回a .

var pony = usr.Properties["OMG_PONIES"]; // Will return a PropertyValueCollection
var value = pony.Value;                  // Will return null and not error
Run Code Online (Sandbox Code Playgroud)

您需要检查值本身,通过null合并运算符的最佳方法:

textBoxFirstName.Text = (usr.Properties["telephoneNumber"].Value 
                            ?? "Not found").ToString();
Run Code Online (Sandbox Code Playgroud)