我尝试从此documentation执行以下操作,以便在启动/停止服务时添加到事件日志中。当我在本地计算机上安装服务并尝试启动它时,构造函数中的代码由于权限而出错:
public MyService()
{
InitializeComponent();
eventLog1 = new System.Diagnostics.EventLog();
if (!System.Diagnostics.EventLog.SourceExists("MySource"))
{
System.Diagnostics.EventLog.CreateEventSource(
"MySource","MyNewLog");
}
eventLog1.Source = "MySource";
eventLog1.Log = "MyNewLog";
}
protected override void OnStart(string[] args)
{
eventLog1.WriteEntry("In OnStart");
}
protected override void OnStop()
{
eventLog1.WriteEntry("In onStop.");
}
以下是事件查看器中显示的错误:
Application: MyService.exe
Framework Version: v4.0.30319
Description: The process was terminated due to an unhandled exception.
Exception Info: System.Security.SecurityException
Stack:
at System.Diagnostics.EventLog.FindSourceRegistration(System.String, System.String, Boolean, Boolean)
at System.Diagnostics.EventLog.SourceExists(System.String, System.String, Boolean)
at System.Diagnostics.EventLog.SourceExists(System.String)
at PharmaLytics.Reforecaster.ReforecasterService..ctor()
at PharmaLytics.Reforecaster.Program.Main()