C# WMI 查询字符串

C# WMI query to string

我想将 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 之前有一个 space:{ 0}。要修复错误,只需删除 space:

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

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

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