【问题标题】:C# WMI query to stringC# WMI 查询到字符串
【发布时间】:2018-02-01 20:11:42
【问题描述】:

我想将 WMI 查询的结果输出到 C# 中的文本框或标签。

但是当我尝试将结果放入textbox.text 时,我得到了System.FormatException

这是我的代码:

using System;
using System.Windows.Forms;
using System.Management;

ManagementScope scope = new ManagementScope();

scope = new ManagementScope(@"\\localhost\root\CIMV2");
scope.Connect();

SelectQuery query = new SelectQuery("SELECT * FROM Win32_OperatingSystem");
ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query);
            
using (ManagementObjectCollection queryCollection = searcher.Get())
{
    foreach (ManagementObject m in queryCollection)
    {
         //this line produces the System.FormatException:
         textBox.Text = string.Format("Computer Name: { 0}", m["csname"]);
     }
} 

【问题讨论】:

  • 错误信息?
  • 去掉{ 0}中的空格
  • 修正格式字符串中的拼写错误Computer Name: { 0} --> Computer Name: {0}.
  • 谢谢大家,这是错字。对不起……也许我睡得少了

标签: c# string textbox label wmi


【解决方案1】:

您的格式字符串的问题是您在占位符中的0 之前有一个空格:{ 0}。要修复错误,只需删除空格:

textBox.Text = string.Format("Computer Name: {0}", m["csname"]);

您还可以稍微简化代码并使用字符串插值(C# 6 的一项功能):

textBox.Text = $"Computer Name: {m["csname"]}";

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-10
    • 1970-01-01
    • 2019-05-03
    • 1970-01-01
    • 2015-07-07
    • 1970-01-01
    相关资源
    最近更新 更多