smashstar
smashstar

Reputation: 81

Elevate user to Admin level to write to Eventlog in .NET

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)?

Upvotes: 0

Views: 4408

Answers (2)

Matt Wilko
Matt Wilko

Reputation: 27322

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.

Upvotes: 0

adrianm
adrianm

Reputation: 14726

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"

Upvotes: 3

Related Questions