您好,这是我在 Stackoverflow 上的第一篇文章。
背景: 我正在构建一个类以使用 WindowsManagementInstrumentation 库来查询 DNS 服务器。
问题: 当我搜索 DNS 服务器上不存在的 DNS 记录时,出现以下错误: System.Management.dll 中出现“System.Management.ManagementException”类型的异常,但未在用户代码中处理
是这条线引起的:
if (search.Get().Count > 0)
在查看这一行时,我发现异常发生在 Count 上。
我不确定为什么会这样。如果我搜索我知道在 DNS 服务器上的 DNS 记录,则 Count 会返回正确的数字并且不会引发错误。如果在服务器上找不到 DNS 记录,我希望 Count 返回 0。我可以做一个 try catch,当它抛出异常时,在我这边处理它,但我觉得这不是正确的方法。有什么想法吗?
调试时出现以下错误信息。
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;
}
抱歉,如果我遗漏了什么,感谢您的帮助。
最佳答案
只是为了让遇到此问题的其他人知道我最终做了什么。我最终将计数检查包装在一个 try catch 中,如果它抛出异常,我将忽略它并只返回一个空的 rrecords 对象,因为搜索没有找到任何东西。
关于在 search.Get().Count 上引发的 C# WMI ManagementException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21295402/