c# - 在C#中获取进程信息的权限

标签 c# .net process

我想做的是使用一种方法获取每个进程的处理时间

//Current Method
public string GetRunningTime(Process p){
   string returnString = "00:00:00:00.00";//DD:HH;MM;SS.ff
   try{
      returnString = DateTime.Now.Subtract(p.StartTime).ToString(@"dd\.hh\:mm\:ss\.ff");//Time now - StartTime. ToString With format
   }catch(Exception){}//Catchs System.ComponentModel.Win32Exception: 'Access is denied'
   return returnString;//returns the string.
}

而且 try-catch 是我在不崩溃的情况下进行数学运算的唯一方法。我想知道是否有办法知道程序是否有权查看 StartTime。所以它会知道不要做数学。

//Example Method
public string GetRunningTime(Process p){
   string returnString = "00:00:00:00.00";
   if(p.HasAcessToStartTime){//Trying to immitate
      returnString = DateTime.Now.Subtract(p.StartTime).ToString(@"dd\.hh\:mm\:ss\.ff");
   }
   return returnString;
}

最佳答案

根据官方文档,StartTime仅通过异常向您显示是否有问题。

NotSupportedException

You are attempting to access the StartTime property for a process that is running on a remote computer. This property is available only for processes that are running on the local computer.

InvalidOperationException

The process has exited.
OR
The process has not been started.

Win32Exception

An error occurred in the call to the Windows function.


有几个选项可以解释这个问题:

  • 请确保您的可执行文件以管理员身份运行,否则您的程序可能会被限制访问某些进程。
  • 正如@Çöđěxěŕ 正确提到的,检查您是否正在尝试从 32 位 调用 64 位 进程。
  • this 中提到的一些进程(例如svchost 系统进程)答案可能是那样的。

关于c# - 在C#中获取进程信息的权限,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63727141/

相关文章:

c# - 进程启动后立即停止

c# - 将 .csv 文件解析为二维数组

.net - OpenXml 和 PowerPoint 入门

windows - 当它可以访问的总内存也被限制为4GB时,Windows如何为多个进程每个分配4GB地址空间

c# - 验证正则表达式而不捕获异常?

c# - 将 MemoryCache 内容持久化到文件

java - 命令行终端在进程上执行并从此进程输入交互

c# - 在删除项目后添加成功消息,在 MVC4 中

c# - 我应该使用什么 sleep 或定时器

c# - 确定控制台应用程序是从命令行还是从 Powershell 运行