c# - 调用 GetOwner 时获取 InvalidOperationException

标签 c# .net wmi wmi-query

在下面的代码中:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Management;
using System.Diagnostics;

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            string javaProcWql = string.Format("SELECT ProcessId, Name, CommandLine FROM Win32_Process WHERE Name = '{0}' AND CommandLine LIKE '%{1}%'", "firefox.exe", "firefox");
            ManagementObjectSearcher mos = new ManagementObjectSearcher(javaProcWql);
            foreach (ManagementObject mo in mos.Get())
            {
                Console.WriteLine(mo["ProcessId"]);
                string[] userinfo = new string[2];
                mo.InvokeMethod("GetOwner", (object[])userinfo);
                Console.WriteLine("ha ha --> " + userinfo[1] + "\\" + userinfo[0]);
            }
        }
    }
}

我得到 InvalidOperationException 并且消息和异常是

"Operation is not valid due to the current state of the object"

这里有什么问题吗?

最佳答案

我找到了解决方案。查询应该是这样的:

string.format( "SELECT * FROM Win32_Process WHERE Name = '{0}' AND CommandLine LIKE '%{1}%'", "firefox.exe", "firefox" )

我的解释是猜测,因为我不是 Windows 或 .NET 编程专家。在原始查询(参见问题)中,我正在选择字段,但通过指定 * 我选择了对象,因此我可以调用它们的方法。

关于c# - 调用 GetOwner 时获取 InvalidOperationException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11811473/

相关文章:

c# - .Net 是否支持柯里化(Currying)泛型?

c# - 如何列出网络计算机上的所有打印机

c# - 以编程方式查找sql​​ server的所有实例

c# - 获取时区的日期时间偏移

c# - 动态查询 SQL Server

c# - 将小数小时添加到时间跨度

c# - 如何检索事件的所有方法?

c# - 获取异常 ""至少一个对象必须实现 icomparable""只有在将方法 ToList() 应用于 IQueryable<> 时

.net - 单点触控 : How to protect my application

c# - 使用 C# 以编程方式更改 ipsec 规则的方法?