首页 > 解决方案 > Windows 服务 - 安装服务时出现 UnauthorizedAccessException 错误 (C#)

问题描述

因此,我尝试在 Visual Studio 2017 中使用 C# 创建服务,并且在尝试安装它时不断收到错误消息。

现在,我的服务中什至没有任何东西,我只想能够安装该服务。我使用 Visual C# > Windows 桌面下的 Windows 服务 (.NET Framework) 模板在 Visual Studio 2017 中创建了一个新项目。然后我通过右键单击 > 添加安装程序添加了安装程序。对于 serviceProcessInstaller1,我将帐户设置为 LocalSystem。而且……就是这样!

现在,我尝试安装它。我打开命令提示符(以管理员身份运行)然后我做了

InstallUtil ServiceTest.exe

事情开始顺利,但随后我收到一条消息:

“安装阶段发生异常。System.UnauthorizedAccessException:尝试执行未经授权的操作。”

什么可能会生成此消息?

我用谷歌搜索并尝试了以下方法:

尽管有这些事情,我仍然遇到同样的错误。我还能做错什么?真的很感激一些建议!

注意:我正在尝试在我的计算机上本地安装此服务。

编辑:根据请求,这里是日志。顺便说一句,我将我的项目命名为“FailedService”,因为我无法让它工作!

InstallUtil.InstallLog

Running a transacted installation.

Beginning the Install phase of the installation.
See the contents of the log file for the C:\Users\first.m.last\source\repos\FailedService\FailedService\bin\Debug\FailedService.exe assembly's progress.
The file is located at C:\Users\first.m.last\source\repos\FailedService\FailedService\bin\Debug\FailedService.InstallLog.

An exception occurred during the Install phase.
System.UnauthorizedAccessException: Attempted to perform an unauthorized operation.

The Rollback phase of the installation is beginning.
See the contents of the log file for the C:\Users\first.m.last\source\repos\FailedService\FailedService\bin\Debug\FailedService.exe assembly's progress.
The file is located at C:\Users\first.m.last\source\repos\FailedService\FailedService\bin\Debug\FailedService.InstallLog.

The Rollback phase completed successfully.

The transacted install has completed.

FailedService.InstallLog

Installing assembly 'C:\Users\first.m.last\source\repos\FailedService\FailedService\bin\Debug\FailedService.exe'.
Affected parameters are:
   logtoconsole = 
   logfile = C:\Users\first.m.last\source\repos\FailedService\FailedService\bin\Debug\FailedService.InstallLog
   assemblypath = C:\Users\first.m.last\source\repos\FailedService\FailedService\bin\Debug\FailedService.exe
Installing service Service1...
Creating EventLog source Service1 in log Application...
Rolling back assembly 'C:\Users\first.m.last\source\repos\FailedService\FailedService\bin\Debug\FailedService.exe'.
Affected parameters are:
   logtoconsole = 
   logfile = C:\Users\first.m.last\source\repos\FailedService\FailedService\bin\Debug\FailedService.InstallLog
   assemblypath = C:\Users\first.m.last\source\repos\FailedService\FailedService\bin\Debug\FailedService.exe
Restoring event log to previous state for source Service1.

标签: c#windowsservicewindows-servicesinstallutil

解决方案


我终于能够解决这个问题。通过使用 SysInternal 的进程监视器,我能够深入了解它。我打开程序并让它记录 InstallUtil.exe 的日志。从那里,我开始搜索任何显示“拒绝访问”的日志。当我整理它们时,我注意到一些有趣的事情:它试图创建一个注册表项,但它一直失败!

所以我进入注册表并创建了一个名为“ServiceTest”的键。之后,我再次运行 InstallUtil 命令,它成功了!

如果其他人遇到问题,解决方案是在以下位置创建一个以您的进程名称命名的密钥:

HKLM\System\CurrentControlSet\Services\EventLog\Application\


推荐阅读