[英]How can I read all current processes and print them in console? / C# ConsoleApp System.Diagnostics
我收到此错误:
(我可以从检查员那里提供更多信息)
System.ComponentModel.Win32Exception: '拒绝访问'
异常最初是在这个调用堆栈中生成的:
System.Diagnostics.ProcessManager.OpenProcess(int, int, bool)
System.Diagnostics.Process.GetProcessHandle(int, bool)
System.Diagnostics.Process.GetProcessTimes()
System.Diagnostics.Process.StartTime.get()
Program.cs 上的 ConsoleApp1.Program.Main(string[])
有代码:
(我从一开始就以管理员身份运行这个程序)
正确答案是如何忽略异常,因为错误的发生是因为即使你有管理员权限也无法读取某些进程
using System.Diagnostics;
namespace ConsoleApp1
{
class Program
{
public class Win32Exception : System.Runtime.InteropServices.ExternalException
{
static void Main(string[] args)
{
var moment = DateTime.Now;
String rh = moment.Hour.ToString();
String rm = moment.Minute.ToString();
String rs = moment.Second.ToString();
Console.Title = moment.ToString("HH:mm:ss");
Process[] localAll = Process.GetProcesses();
/// Process[] procesos;
///procesos = Process.GetProcesses();
///
foreach (Process p in localAll)
{
/// Console.WriteLine(p.ProcessName);
try
{
var tmp = p.StartTime;
String h = p.StartTime.ToString("HH");
String m = p.StartTime.ToString("mm");
String s = p.StartTime.ToString("ss");
int x = Int32.Parse(rh);
int y = Int32.Parse(h);
if (x <= y)
{
Console.WriteLine($"{p.ProcessName} TIME= {p.StartTime.ToString("HH:mm:ss")}");
}
}
catch (Win32Exception)
{
continue;
}
}
Console.ReadKey();
}
}
}
}
您不需要声明继承System.Runtime.InteropServices.ExternalException
的类。 您只需要使用try...catch
来捕获异常System.ComponentModel.Win32Exception
。 只需像这样修改代码。
class Program
{
static void Main(string[] args)
{
// Code omitted
// ...
// Code omitted
foreach (Process p in localAll)
{
try
{
// Code omitted
// ...
// Code omitted
}
catch (System.ComponentModel.Win32Exception)
{
continue;
}
}
Console.ReadKey();
}
}
您尝试将 catch 异常替换为Exception
吗?
catch (Exception)
{
continue;
}
如果您想保留Win32Exception
另一种方法是将自定义异常的继承更改为
public class Win32Exception : System.ComponentModel.Win32Exception
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.