【发布时间】:2017-12-26 18:50:07
【问题描述】:
我正在编写一个服务,我需要在其中获取当前处于活动状态的进程的文件名。
我有类似于下面的代码(我已经去掉了完整性检查)
Process currentProcess = GetActiveProcess();
ProcessModule currentModule = currentProcess.MainModule;
string FileName = currentModule.FileName.ToLower();
当我编译它并作为一个 winforms 应用程序运行时,它就像一个魅力。
但是,当我将完全相同的代码作为服务运行时(无论我作为 LocalSystem 用户运行服务还是作为应用程序运行代码的管理员用户),它都会在第二行引发异常:
无法枚举进程模块
我已经尝试过:
-
添加:
[PermissionSetAttribute(SecurityAction.LinkDemand, Name = "FullTrust")] [HostProtectionAttribute(SecurityAction.LinkDemand, SharedState = true, Synchronization = true, ExternalProcessMgmt = true, SelfAffectingProcessMgmt = true)] [PermissionSetAttribute(SecurityAction.InheritanceDemand, Name = "FullTrust")] class WindowsService : ServiceBase 设置服务以管理员用户身份启动
-
添加到 app.manifest:
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
这些都不起作用。 我需要做什么才能获得 MainModule?
【问题讨论】:
-
你得到什么特定的异常类型?你看过this吗?
-
是的,我愿意。异常是 Win32Exception 但对我来说没有意义,因为我已经在 Windows XP 32bit 和 Windows 7 32bit 上检查过它。
-
我检查了其他从 Process 获取文件名的方法,结果相同,错误略有不同 - 访问被拒绝。即使服务使用管理员凭据运行。因此,可以肯定的是,作为服务是无法访问 Process.MainModule 的一个原因。