【问题标题】:C# WMI ManagementException thrown on search.Get().Count在 search.Get().Count 上抛出 C# WMI ManagementException
【发布时间】: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() 周围不会有问题。

标签: c# dns wmi


【解决方案1】:

只是这样任何遇到这个问题的人都知道我最终做了什么。我最终将计数检查包装在 try catch 中,如果它引发异常,我将忽略它并返回一个空的 rrecords 对象,因为搜索没有找到任何东西。

【讨论】:

  • 我们也是这样做的(就像 10 年前一样)。看起来不错。身份证
猜你喜欢
  • 2013-11-16
  • 2019-11-11
  • 2015-01-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多