【问题标题】:Reading ManagementObject objects in a collection into typed variables将集合中的 ManagementObject 对象读入类型变量
【发布时间】:2015-05-15 14:41:12
【问题描述】:

我收藏了ManagementObjects。管理对象的属性有不同的类型:int、string、array、DateTime等。

我想将属性值读入适当的变量类型。

ManagementScope manScope = new ManagementScope(@"\\.\root\virtualization\v2"); 
manScope.Connect();
ObjectQuery queryObj = new ObjectQuery("SELECT * FROM Msvm_ComputerSystem");
ManagementObjectSearcher vmSearcher = new ManagementObjectSearcher(manScope, queryObj);

ManagementObjectCollection vmCollection = vmSearcher.Get();

foreach (ManagementObject vm in vmCollection) {
    **//Fine so far.  This is not a question about iteration.**
    //Now I want to so something programmatic with the values.

    //If it is a string, this is fine:
    string myString = vm["Description"].ToString();

    //If it is an integer, I can go like this:
    int myInt =int.Parse(vm["EnabledState"].ToString());
    //But surely c# has a better way than that? Turn it into a string and then an int?

    //If it is DateTime, I have no idea what to do - DateTime.Parse() doesn't work:
   //DateTime myDate = DateTime.Parse(vm["LastSuccessfulBackupTime"].ToString());

}

我已阅读文档(其中没有一个示例)。 我使用了 WMI Code Creator,它也无济于事,因为它只是将所有内容都放入控制台: Console.WriteLine("InstallDate: {0}", queryObj["InstallDate"]);

【问题讨论】:

  • 对不起@UweKeim,但那篇文章没有帮助,WMI 代码创建器也没有帮助。我已经更新了问题以澄清它。

标签: c# wmi


【解决方案1】:

这是非常不寻常的要求,但我仍然建议查看类详细信息Msvm_computersystem 并创建具有相同数据类型的变量。 获取集合中的数据后,您可以尝试将其解析为适当的变量。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-11-13
    • 2011-04-01
    • 2021-01-08
    • 1970-01-01
    • 2011-08-04
    • 2015-02-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多