当foreach时,我收到无效的查询错误(mos.Get()中的ManagementObject mo)

时间:2018-08-15 20:55:57

标签: c#

using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Management;

namespace NetPrimate_Provisioning_Tool_1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btnGet_Click(object sender, EventArgs e)
        {

            foreach (string cpu in GetComponents("WIN32_Processor", "Name"))
            {
                txtInfo.AppendText("CPU:" + cpu + Environment.NewLine);
            }

            foreach (string gpu in GetComponents("WIN32_VideoController", "Name"))
            {
                txtInfo.AppendText("GPU:" + gpu + Environment.NewLine);
            }

            foreach (string os in GetComponents("WIN32_OperatingSystem", "Caption"))
            {
                txtInfo.AppendText("OS:" + os);
                if(Environment.Is64BitOperatingSystem)
                {
                    txtInfo.AppendText("64Bit" + Environment.NewLine);
                }
                else
                {
                    txtInfo.AppendText("32Bit" + Environment.NewLine);
                }
            }

            string ram = GetComponents("WIN32_ComputerSystem", "TotalPhysicalMemory")[0];

            double db_ram = Convert.ToDouble(ram) / 1073741824;

            int size = (int)Math.Ceiling(db_ram);

            txtInfo.AppendText("RAM:" + size.ToString() + "GB");

        }

        public List<string> GetComponents(string hwclass, string syntax)
        {
            List<string> details = new List<string>();

            ManagementObjectSearcher mos = new ManagementObjectSearcher("root\\CIMV2", "SELECT*FROM " + hwclass);

            foreach (ManagementObject mo in mos.Get())    ##ERROR HERE##

            {
                details.Add(mo[syntax].ToString());
            }

            return details;
        }

    }

}

嗨,我在标记为(## ERROR HERE ##)的行上收到的所有即时消息都是无效的,但我似乎找不到任何人可以提供帮助的修复程序。该脚本应查看系统并获取系统信息。

Photo of the Program

1 个答案:

答案 0 :(得分:1)

您的查询不正确,您需要在令牌"SELECT * FROM " + hwclass之间插入空格,然后才能使用。