.net 如何将事件日志保存到csv文件中

v09wglhw  于 2023-01-31  发布在  .NET
关注(0)|答案(3)|浏览(188)

我正在尝试将从事件查看器获取的日志文件结果保存到csv文件中,并确保其不重复
有什么建议吗
这是读取日志文件的代码

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();

    }
}
ou6hu8tu

ou6hu8tu1#

要将日志保存到csv文件中,您可以按照以下答案操作:Writing data into CSV file in C#
在您的情况下,它应该如下所示:

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());

你可以用“,”而不是“;“以使其例如对于Excel可读。
但是我还是不明白你说的不应该打印副本是什么意思。每一行都有不同的事件ID和时间戳,所以即使消息出现多次,也会有不同的示例。

tpgth1q7

tpgth1q72#

我有类似的要求读取evtx文件并转换为csv,我尝试了上面的代码,它不为我工作。该代码不进入foreach块。

using System;
using System.Text;

class Program
{
    static void Main(string[] args)
    {        
   System.Diagnostics.EventLog log = new      System.Diagnostics.EventLog("ForwardedEvents");
var csv = new StringBuilder();
foreach (System.Diagnostics.EventLogEntry entry in log.Entries)
{
    csv.AppendLine($"{entry.Index};{entry.Source};{entry.EntryType};{entry.EntryType};{entry.TimeGenerated};{entry.UserName};{entry.Message}");
    Console.WriteLine("Index:" + entry.Index);
}
 Console.WriteLine("Index:");  

  
    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.InstanceId);
            Console.WriteLine("TimeGenerated:"+entry.TimeGenerated);
            Console.WriteLine("User Name:"+entry.UserName);
            Console.WriteLine("Message:"+entry.Message);
            Console.WriteLine("--------");
        }
    }
    Console.WriteLine("Done");
    Console.ReadLine();
}

}

ykejflvf

ykejflvf3#

我已经附上了在线

中试用过的示例代码的屏幕截图

相关问题