目标:在MVC 5 / C#中,我尝试使用WMI来读取某些进程是否在我的LAN上的计算机上运行(然后由用户检查/取消选中复选框控件来启动/停止它们)。 当应用程序在IIS托管环境中运行时,我们得不到任何结果 - 显示正在运行的进程的所有复选框都未选中,但我们知道这是不正确的。从Visual Studio在应用程序中执行相同的代码时,将返回正确的结果。 在IIS上,应用程序的应用程序池在ApplicationPoolIdentity下运行。
如果有任何帮助,我将不胜感激。
以下是确定相关进程是否正在运行的方法:
public static List<KeyValuePair<string, bool>> GetNodeProcesses(string NetworkName, List<Application> apps, string NodeReply)
{
//Get the list of processes and assign false to each process
List<KeyValuePair<string, bool>> list = new List<KeyValuePair<string, bool>>();
if (NodeReply == "success")
{
for (int i = 0; i < apps.Count; i++)
{
list.Add(new KeyValuePair<string, bool>(apps[i].ProcessName, false));
//Iterate through processes that are running and check each process for a match in the list variable, if a match is found assign true to the item in the list variable
try
{
ConnectionOptions connOptions = new ConnectionOptions();
connOptions.Impersonation = ImpersonationLevel.Impersonate;
connOptions.EnablePrivileges = true;
ManagementScope manScope = new ManagementScope(String.Format(@"\\{0}\ROOT\CIMV2", NetworkName), connOptions);
manScope.Connect();
using (var searcher = new ManagementObjectSearcher(manScope, new SelectQuery("select Name from Win32_Process")))
{
foreach (ManagementObject mo in searcher.Get())
{
string process = mo["Name"].ToString();
if (apps.Any(p => p.ProcessName == process))
{
list.Remove(new KeyValuePair<string, bool>(process, false));
list.Add(new KeyValuePair<string, bool>(process, true));
}
}
}
}
catch (Exception ex)
{
list.Add(new KeyValuePair<string, bool>("An error occurred getting processes running on " + NetworkName + ":" + Environment.NewLine + ex.Message, false));
}
}
else
{ list.Add(new KeyValuePair<string, bool>("", false)); }
return list;
}