在search.Get()上抛出C#WMI ManagementException。计数

时间:2014-01-22 22:30:57

标签: c# dns wmi

您好,这是我在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;
}

很抱歉,如果我遗漏了任何内容,感谢您的帮助。

1 个答案:

答案 0 :(得分:2)

正是如此,遇到这种情况的任何人都知道我最终在做什么。我最终将try计数检查包装在try catch中,如果它抛出异常,我会忽略它并返回一个空的rrecords对象,因为搜索没有找到任何东西。