C#: Simple Windows Service gives Security Exception

后端 未结 4 607
不思量自难忘°
不思量自难忘° 2021-02-13 13:43

I am doing the walkthrough in the following link: http://msdn.microsoft.com/en-us/library/zt39148a%28VS.80%29.aspx

I have followed it exactly, line by line. I installed

4条回答
  •  后悔当初
    2021-02-13 14:35

    The EventLog.SourceExists method is what will be causing this exception. The most common reason being it tries to access ALL the event logs (including the Security log) which by default in Vista you will not have permissions for. Another reason can be if the source you are looking for is not found in the event log (which I find rather odd!).

    A work-around:

    bool sourceFound = false;
    try
    {
        sourceFound = EventLog.SourceExists("MySource");
    }
    catch (SecurityException)
    {
        sourceFound = false;
    }
    

    Another option is to simply elevate your permissions, however, as you where following the tutorial step by step your service would be running under the LocalService account (which again won't have permissions for this particular method). Hence, you will find on the MSDN documentation the solution is to check whether the event source exists in the ServiceInstaller and if it doesn't, create the source in the installer.

提交回复
热议问题