在字典变量上使用循环

时间:2019-06-24 12:09:21

标签: c#

我正在使用字典变量,并在其中添加所有服务名称,并调用foreach循环以遍历系统并获取所有服务。

我已经使用List使用了此代码,它工作得非常好,现在我正在使用Dictionary变量,并且无法遍历所有服务。

foreach(ServiceController service in ServiceController.GetServices()) {
  string serviceName = service.ServiceName;
  string serviceDisplayName = service.DisplayName;
  string serviceType = service.ServiceType.ToString();
  string status = service.Status.ToString();

  Dictionary<int, string> output = new Dictionary<int, string>();

  if (service.Status == ServiceControllerStatus.Running) {
    string exists = null; {
      output.Add(1, "RUNNING SERVICE: ");
      output.Add(2, "Service Name: " + serviceName);
      output.Add(3, "Service Display Name: " + serviceDisplayName);
      output.Add(4, "Service Type: " + serviceType);
      output.Add(5, "Service Status: " + status);

      if (output.ContainsKey(1) == true) {
        exists = (output[1]);
      }
      if (output.ContainsKey(2) == true) {
        exists = (output[2]);
      }
      if (output.ContainsKey(3) == true) {
        exists = (output[3]);
      }
      if (output.ContainsKey(4) == true) {
        exists = (output[4]);
      }
      if (output.ContainsKey(5) == true) {
        exists = (output[5]);
      }

    }
  } else {}

  foreach(var i in output) {
    var result = string.Join(Environment.NewLine, output);
    Result.Set(context, result);
  }
}

输出:

[1, RUNNING SERVICE: ]
[2, Service Name: ZAtheros Bt and Wlan Coex Agent]
[3, Service Display Name: ZAtheros Bt and Wlan Coex Agent]
[4, Service Type: Win32OwnProcess]
[5, Service Status: Running]

现在,此代码为我提供了此输出。这只是一项服务信息,我需要系统中存在的所有服务。

0 个答案:

没有答案