简体   繁体   中英

Reading local event log?

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 the ToString method on that variable. The default implementation of ToString is to return the name of the class. (Hence the repeated System.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:

static void Main(string[] args)
{

    StringBuilder eventLogText = new StringBuilder();
    try
    {
        var eventLog = new EventLog("Application");
        var tenMostRecentEvents = eventLog.Entries
                                            .Cast<EventLogEntry>()
                                            .Reverse()
                                            .Take(10);
        foreach (EventLogEntry entry in tenMostRecentEvents)
        {
            eventLogText.AppendLine(String.Format("{0} - {1}: {2}", 
                                          entry.Source, 
                                          entry.TimeWritten, 
                                          entry.Message));
        }

        Console.WriteLine(eventLogText.ToString());
    }
    catch (System.Security.SecurityException ex)
    {
        Console.WriteLine(ex);
    }
    Console.ReadLine(); 
}

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 information

Hope it helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM