C#导出 Windows 事件日志

using System;
using System.Windows.Forms;
using System.Diagnostics;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            System.IO.File.WriteAllText(@"c:\eventlog.txt", GetEventLogs(LogName.Application, "ASP.NET 2.0.50727.0", "发生了验证错误", DateTime.MinValue));
        }

        /// <summary>
        /// 日志名
        /// </summary>
        enum LogName
        {
            Application,//应用程序
            Security,//安全
            System//系统
        }

        /// <summary>
        /// 获取系统日志
        /// </summary>
        /// <param name="logname">日志名</param>
        /// <param name="source">事件源</param>
        /// <param name="message">描述</param>
        /// <param name="generated">创建时间</param>
        /// <returns></returns>
        private string GetEventLogs(LogName logname, string source, string message, DateTime generated)
        {
            EventLog appLog = new EventLog(logname.ToString());
            EventLogEntryCollection entries = appLog.Entries;
            EventLogEntry entry;
            string result = string.Empty;

            //从最新日志开始
            for (int i = entries.Count - 1; i >= 0; i--)
            {
                entry = entries[i];

                if (!string.IsNullOrEmpty(source))
                    if (entry.Source != source)
                        continue;

                if (!string.IsNullOrEmpty(message))
                    if (entry.Message.IndexOf(message) == -1)
                        continue;

                if (DateTime.Compare(generated, entry.TimeGenerated) > 0)
                    continue;

                result += entry.Message + "\r\n" + "--------------------------------------------------------\r\n\r\n";
            }

            return result;
        }
    }
}


评论: 0 | 引用: 0 | 查看次数: 6481
发表评论
登录后再发表评论!