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

本文介绍如何使用C#中的System.Diagnostics.EventLog类来读取和写入Windows系统的事件日志,包括应用程序和系统日志,并提供了一个简单的示例程序。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 应用程序想向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);
}

程序运行图如下:

797d79e15dec7a2ed7737ef744d47627.png

f33c7a2c62b0d7362d46de8e30f802a8.png

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

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

程序运行效果如下

3fbd30e4cb21af525e35fec437511133.png

441ee531b10fbc7001b901ca55cb0ce2.png

下面复习几个快捷键:

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

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值