【发布时间】:2014-01-22 22:30:57
【问题描述】:
您好,这是我在 Stackoverflow 上的第一篇文章。
背景: 我正在构建一个类来使用 WindowsManagementInstrumentation 库来查询 DNS 服务器。
问题: 当我搜索 DNS 服务器上不存在的 dns 记录时,我收到以下错误: System.Management.dll 中出现“System.Management.ManagementException”类型的异常,但未在用户代码中处理
这是由这一行引起的:
if (search.Get().Count > 0)
在查看这一行时,我发现异常出现在 Count 上。
我不知道为什么会这样。如果我搜索我知道在 DNS 服务器上的 DNS 记录,则 Count 返回正确的数字并且不会引发错误。如果在服务器上找不到 DNS 记录,我希望 Count 返回 0。我可以尝试捕获,当它抛出异常时,我会在最后处理它,但我觉得这不是正确的方法。有什么想法吗?
我在调试时收到以下错误信息。
Count 'Count' threw an exception of type 'System.Management.ManagementException' int {System.Management.ManagementException}
base {"Generic failure "} System.SystemException {System.Management.ManagementException}
base {"Generic failure "} System.Exception {System.Management.ManagementException}
Data {System.Collections.ListDictionaryInternal} System.Collections.IDictionary {System.Collections.ListDictionaryInternal}
HelpLink null string
HResult -2146233087 int
InnerException null System.Exception
Message "Generic failure " string
Source "System.Management" string
StackTrace " at System.Management.ManagementException.ThrowWithExtendedInfo(ManagementStatus errorCode)\r\n at System.Management.ManagementObjectCollection.ManagementObjectEnumerator.MoveNext()\r\n at System.Management.ManagementObjectCollection.get_Count()" string
ErrorCode Failed System.Management.ManagementStatus
完整方法:
public List<ManagementObject> GetRecords(string domain, string name, string type)
{
//Object to hold list of RRecords/DNS Records
List<ManagementObject> rrecords = new List<ManagementObject>();
//Init properites for the given type
Properties propertiesStruct = new Properties(type);
//Query
string query = "SELECT * FROM " + propertiesStruct.Table + " WHERE DomainName = '" + domain.ToLower() + "' AND OwnerName ='" + name.ToLower() + "." + domain.ToLower() + "'";
//Search for results
ManagementObjectSearcher search = new ManagementObjectSearcher(this.scope, new ObjectQuery(query));
//Make sure we have something and if we do loop through them to grab the data
if (search.Get().Count > 0)
{
foreach (ManagementObject results in search.Get())
{
rrecords.Add(results);
}
}
return rrecords;
}
对不起,如果我错过了什么,并感谢您的帮助。
【问题讨论】:
-
不确定这是否会有所帮助,但我经常在 Powershell 中使用 WMI 调用,并且我发现即使返回一个对象,.Count 属性有时也可能为空。我认为这会引发更明确的异常,但我会首先检查 Count 属性是否为空。作为旁注,我认为将 try catch 包裹在 search.Get() 周围不会有问题。