1

I'm trying to save the result of log files that I get from Event viewer into a csv file and make sure its not duplicated

any suggestions please

this my code for reading the log file

    using System;
using System.Text;

class Program
{
    static void Main(string[] args)
    {
       
        System.Diagnostics.EventLog log = new
        System.Diagnostics.EventLog("System");


        foreach (System.Diagnostics.EventLogEntry entry in log.Entries)
        {


            {
                Console.WriteLine("Index:" + entry.Index);
                Console.WriteLine("source:"+entry.Source);
                Console.WriteLine("Level:"+entry.EntryType);
                Console.WriteLine("Event ID:"+entry.EventID);
                Console.WriteLine("TimeGenerated:"+entry.TimeGenerated);
                Console.WriteLine("User Name:"+entry.UserName);
                Console.WriteLine("Message:"+entry.Message);
                Console.WriteLine("--------");
            }
        }

        Console.WriteLine("Done");
        Console.ReadLine();

    }
}
2
  • Your problem is that you can't save to a csv file or that there are duplicates? Commented Aug 11, 2022 at 13:37
  • @Patrick i want to save it into csv and make sure no duplicated will happens Commented Aug 11, 2022 at 13:39

2 Answers 2

1

To save your logs to a csv you can follow this answer: Writing data into CSV file in C#

In your case it should look something like this:

var log = new EventLog("System");
var csv = new StringBuilder();
foreach (EventLogEntry entry in log.Entries)
{
    csv.AppendLine($"{entry.Index};{entry.Source};{entry.EntryType};{entry.EntryType};{entry.TimeGenerated};{entry.UserName};{entry.Message}");
}
File.WriteAllText("test.csv", csv.ToString());

It can be that you ne "," instead of ";" to make it readable for excel for example.

But I still not get what you mean by it should not print duplicates. Each line has a different event id and timestamp, so even if the message is there multiple times, there are different instances.

Sign up to request clarification or add additional context in comments.

4 Comments

the code work good without error but the file still empty
Did you also find the file? It is saved in the debug folder, you can also have another file path there like "C:/test.csv". It worked for me and wrote alle the logs into the file.
last question is there anyway to separate events from each other on the file to make it readable
I have similar requirement to read evtx file and convert to csv, I tried above code and it does'nt work for me
0

I have attached the screenprint for tried sample code in online enter image description here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.