C#应用程序对windows日志操作读写

应用程序想向windows系统读取系统或应用程序日志时需用到System.Diagnostics.EventLog类。.

1,读日志

private void button1_Click(object sender, EventArgs e)
{
    Task1();//多线程运行
    textBox1.Text = "我第一更新到界面textbox上面 \r\n";//会第一个显示到界面
}
private async Task Task1()
{
    EventLog eventLog = new EventLog(); //创建日志实例
    eventLog.Log = "System";//应用程序日志为Application,系统日志为System
    EventLogEntryCollection collection = eventLog.Entries; //获取可遍历collection
    label1.Text = $"一共有:{ collection.Count}记录";
    string resul = "";
    await Task.Run(() =>
    {
        foreach (EventLogEntry item in collection)
        {
            resul += $" \r\n {item.Message}";
        }
    });
    textBox1.AppendText(resul);
}

程序运行图如下:

C#应用程序对windows日志操作读写

C#应用程序对windows日志操作读写

2,写日志也是用System.Diagnostics.EventLog类。

private void button1_Click(object sender, EventArgs e)
{
    EventLog eventLog = new EventLog();
    eventLog.Source = textBox1.Text;
    eventLog.WriteEntry(textBox2.Text);
}

程序运行效果如下:

C#应用程序对windows日志操作读写

C#应用程序对windows日志操作读写

下面复习几个快捷键:

  1. 注释代码:选中代码 ctrl+K+C
  2. 解除注释代:选中代码 ctrl+K+U
  3. 快速整理代码:ctrl+K+F
  4. 删除多余的空格:ctrl+H打开查找替换窗口,输入^\s*\n ,勾选正则表达式,全替换为空即可。
  5. 强制智能感知:ctrl+J
  6. 强制显示参数信息:ctrl+shift+空格
  7. 插入代码段:ctrl+K+S
  8. 折叠光标所有函数或代码断(也能展开代码):ctrl+M+M