I want to read the Event Log on a remote computer to check for errors during testing. Here's some relevant code:
public bool CheckEventLogs(DateTime start)
{
EventLog myEventLog = new EventLog("CustomLog", "ServerName");
bool errorFound = false;
foreach (EventLogEntry entry in myEventLog.Entries)
{
if (entry.EntryType == EventLogEntryType.Error && entry.TimeGenerated >= start)
{
Console.WriteLine("Error in Event Log:\n" + entry.Message + "\n");
errorFound = true;
}
}
return errorFound;
}
Currently, this code throws an exception (Attempted to perform an unauthorized operation). According to MSDN, I need EventLogPermission, but I have been struggling to find any examples of how to use this permission. Does anyone have an example of how to do this?
Edit: Response to Comments
Thank you all for the comments - here is the additional information requested:
The exception is thrown from the foreach
statement. Specifically, when stepping through the code it thrown in the step after when in
is highlighted. It seems that I was able to create the event log object but I'm not able to access the entries in the event log.
My account does not have permission to read the event log on the target system, but I have credentials for an account which does. When connecting manually through the event viewer there is an option to connect as another user. After doing this manually, then my code ran without a problem. However, I cannot rely doing it manually every time this program runs. What I need is a way to connect as another user programmaticly. I thought that the EventLogPermission
would be the way to do that, but maybe there is another way. If anyone knows how to connect to a remote log as a different user in C#, that would be exactly what I was looking for.