Here i am trying to read the local system event log using c# using this code-
string eventLogText = "";
try
{
var eventLog = new EventLog("logname", "machinename");
foreach (var entry in eventLog.Entries)
{
eventLogText += entry;
}
}
catch (Exception eg)
{
MessageBox.Show(eg.Message);
}
It is working well, but the problem is, in the variable eventLogText i get only System.Diagnostics.EventLogEntry repeatedly, may be this is very common mistake but i don't know what to do as i am very new to the c# as well as programming too.
Secondly i want to know that if a system is not logged in using Administrator account, in that case reading event log will cause any exception or error and if it will what will be the solution for it ?
Need help.Thanks in advance.
Regarding your first question, you are just adding the variable
entry
to the string, which is calling theToString
method on that variable. The default implementation of ToString is to return the name of the class. (Hence the repeatedSystem.Diagnostics.EventLogEntry
output)You will need to use the members in the
EventLogEntry
class to retrieve the data you are interested in. For example, this console application will print the source and message of the first 10 entries in the Application event log:Regarding your second question, your code will need the appropriate permissions to read that event log. For example, if I change the code read the Security event log using this line
var eventLog = new EventLog("Security");
I will receive a security exception. You can check this answer for more informationHope it helps!