Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# C WMI查询到字符串_C#_String_Textbox_Label_Wmi - Fatal编程技术网

C# C WMI查询到字符串

C# C WMI查询到字符串,c#,string,textbox,label,wmi,C#,String,Textbox,Label,Wmi,我想将WMI查询的结果输出到C中的文本框或标签 但当我尝试将结果放入textbox.text时,会得到一个System.FormatException 这是我的密码: using System; using System.Windows.Forms; using System.Management; ManagementScope scope = new ManagementScope(); scope = new ManagementScop

我想将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}中的0前面有一个空格。要修复错误,只需删除空格:

textBox.Text = string.Format("Computer Name: {0}", m["csname"]);
您还可以稍微简化代码,并使用字符串插值作为C 6功能:

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

错误消息?清除{0}中的空格,修复格式字符串Computer Name:{0}->Computer Name:{0}中的拼写错误。多亏了大家,这就是拼写错误。我很抱歉。。。也许我睡得少一点