0

I am working on a Windows .NET application and I want to write to the Eventlog.

Public Shared Sub WriteExceptionToEventLog(ByVal message As String)
        Dim cs As String = "TESTLOG"
        Dim elog As New EventLog()
        Dim sourceExist As Boolean

        Try
            sourceExist = EventLog.SourceExists(cs)
        Catch ex As Exception
            sourceExist = False
        End Try

        If Not sourceExist Then
            Dim ev As New EventLogPermission(EventLogPermissionAccess.Administer, ".")
            ev.PermitOnly()
            EventLog.CreateEventSource(cs, "TESTLOG")
        End If
        elog.Source = cs
        elog.EnableRaisingEvents = True
        EventLog.WriteEntry(cs, message, EventLogEntryType.[Error])

    End Sub

But this is not working as the user in Windows 7 need Admin previlage to write to Eventlog. The same was successful when I executed the application with "Run ad Admin" mode.

So is there any way to give Admin privilege for a code segment in vb.net (other than impersonation)?

Marcel N.
  • 13,726
  • 5
  • 47
  • 72
smashstar
  • 81
  • 1
  • 16

2 Answers2

3

You just need admin rights to create the event source not to write to it.

Create the source when installing or manually in an elevated command prompt.

eventcreate /ID 1 /L APPLICATION /T INFORMATION /SO mysource /D "created mysource"
adrianm
  • 14,468
  • 5
  • 55
  • 102
  • Thanks adrianm, but i have several small application in a solution, and want to create the Eventsource dynamically using code – smashstar Jul 06 '12 at 06:47
  • Then you need to run the applications with admin rights or change the security policy. Why not let all your applications use the same source? – adrianm Jul 06 '12 at 07:00
0

You can change the app.manifest requestedExecutionLevel to requireAdministrator - this will force an UAC prompt when the application runs and the application will only run if it can run as admin. (To change this go to Project Properties>Application tab>View Windows Settings)

If your application frequently needs admin rights then this is really the only way.

If you only sometimes need admin rights then you could restart you application with higher privileges at the point when you need to write to the event log. Have a look at this informative article about using UAC in .NET applications for more information on this.

Matt Wilko
  • 26,994
  • 10
  • 93
  • 143