读取Windows EventLog

  • 读取Windows EventLog
    • 通过EventLog获取日志
      • 通过EventLog获取日志,Sample1
      • 通过EventLog获取日志,Sample2
    • Eventing.Reader读取特定路径或Log名称的完整示例
      • 在App.config中设定参数
      • 读取App.config中设定的参数
      • 基本代码(读取、分析、备份)
    • 压缩Helper

读取Windows EventLog

我在尝试读取用户VDI连接数据,以便统计用户的访问时长的过程中,首先发现 .evtx文件只能用Windows事件查看器不会乱码,其次发现通过System.Diagnostics.EventLog找不到VDI的log,也就没办法自动获取VDI数据,不得已:把VDI evtx文件复制到指定文件夹,程序到指定文件夹读取,此时需要用System.Diagnostics.Eventing.Reader然后压缩备份到另一个文件夹(不同的事件ID有不同的属性内容,详细的属性内容可以参考Windows事件查看器的某条Log的详细信息,如此就知道哪个属性Value是我们想要的了.
这里是:建议用Eventing.Reader读取Windows相关EventLog

通过EventLog获取日志

通过EventLog获取日志,Sample1

先展示下面的 代码片.

// 如果已经引用using System.Diagnostics,则可以直接写:EventLog[]
System.Diagnostics.EventLog[] EventLogList;
//指定電腦上的所有事件記錄檔,並建立含有清單的 EventLog 物件陣列
EventLogList= System.Diagnostics.EventLog.GetEventLogs(".");
//不管是在我个人电脑还是在VDI服务器上:EventLogList.Length都是9
Console.WriteLine("Number of logs on computer: " + EventLogList.Length);
//显示Log名称和每个Log的事件个数(Security需要管理员权限)
foreach (System.Diagnostics.EventLog log in EventLogList){Console.WriteLine();Console.WriteLine("  Log name = \t {0}", log.Log);Console.WriteLine("  Number of event log entries = {0}", log.Entries.Count.ToString());// "Application"应用程序, "Security"安全, "System"系统//以Application为例,大同小异if (log.Log=="Application"){DateTime EventCreateTime;string EventID, EventMessage, Param1, Param2, Param3;foreach (EventLogEntry eventLog in log.Entries){EventID = eventLog.InstanceId.ToString();if (EventID == "4625"){EventMessage = eventLog.Message;EventCreateTime = eventLog.TimeGenerated;Param1 = eventLog.ReplacementStrings[0].ToString();Param2 = eventLog.ReplacementStrings[1].ToString();Param3 = eventLog.ReplacementStrings[2].ToString();}}}}

通过EventLog获取日志,Sample2

先展示下面的 代码片.

//"Application"应用程序, "Security"安全, "System"系统
EventLog myEventLog = new EventLog("Application");
Console.WriteLine("  Number of Eventlog = {0}", myEventLog.Entries.Count.ToString());
//
DateTime EventCreateTime;
string EventID, EventMessage, Param1, Param2, Param3;foreach (EventLogEntry eventLog in myEventLog.Entries){EventID = eventLog.InstanceId.ToString();if (EventID == "4625"){EventMessage = eventLog.Message;EventCreateTime = eventLog.TimeGenerated;Param1 = eventLog.ReplacementStrings[0].ToString();Param2 = eventLog.ReplacementStrings[1].ToString();Param3 = eventLog.ReplacementStrings[2].ToString();}}

Eventing.Reader读取特定路径或Log名称的完整示例

在App.config中设定参数

注意 appSettings中的内容.

<appSettings><!--VDI日志目录路径--><add key="VDILogPath" value="C:\EventLog\VDI"/><!--VDI日志名称--><add key="VDILogName" value="VDILog.evtx"/><!--VDI日志备份目录路径--><add key="LogBackupPath" value="C:\EventLog\Backup"/></appSettings>

读取App.config中设定的参数

string VDILogPath = ConfigurationManager.AppSettings["VDILogPath"].ToString();
string VDILogName = ConfigurationManager.AppSettings["VDILogName"].ToString();
string LogBackupPath = ConfigurationManager.AppSettings["LogBackupPath"].ToString();

**注意要引用:System.Configuration.dll;**否则ConfigurationManager无效

基本代码(读取、分析、备份)

注意要引用using System.Diagnostics.Eventing.Reader

static void Main(string[] args)
{//读参数中的VDILog所在文件夹
string VDILogPath = ConfigurationManager.AppSettings["VDILogPath"].ToString();
//读VDILog的名称
string VDILogName = ConfigurationManager.AppSettings["VDILogName"].ToString();
//拼接在一起
string eventLogLocation = VDILogPath + "\\" + VDILogName;
Console.WriteLine("VDI Log Path: "+ eventLogLocation );
//C:\EventLog\VDI\VDILog.evtx
//EventLogQuery后面的参数示例,一个是通过指定文件夹 一个是通过指定Log名称
EventLogQuery eventLogQuery = new EventLogQuery(eventLogLocation, PathType.FilePath);
//EventLogQuery eventLogQuery = new EventLogQuery("Application", PathType.LogName);try{//LogName=eventLogLocationEventLogReader eventlogReader = new EventLogReader(eventLogQuery);// Display event infoDisplayEventAndLogInformationForVDI(eventlogReader, eventLogLocation);}catch (EventLogNotFoundException e){Console.WriteLine("Could not Find the VDI Log to Query! " + e.Message);return;}
}
private static void DisplayEventAndLogInformationForVDI(EventLogReader logReader, string SourceLocation){//VDI 303事件所需要的变量string LoginDateTime = "";Int32 ConnectedSecond = 0;string LoginDate = "";string LoginTime = "";string UserID = "";int Count303Type = 0;//303事件数量int InsertCount = 0;//成功插入DB的数量int TotalCount = 0;//EventLog中的事件数量string DBResult = "Ok";// InitDBInfo();初始化数据库省略if (DBResult != "Ok"){Console.WriteLine("DB Connect Fail: {0}", DBResult);}else{for (EventRecord eventInstance = logReader.ReadEvent();null != eventInstance; eventInstance = logReader.ReadEvent()){TotalCount++;Console.WriteLine("-----------------------------------------------------");Console.WriteLine("Event ID: {0}", eventInstance.Id);//Link DB For Query or Insertif (eventInstance.Id.ToString() == "303"){Count303Type++;LoginDateTime = eventInstance.TimeCreated.ToString();//2022/4/30 13:34:39LoginDate = Convert.ToDateTime(LoginDateTime).ToString("yyyy-MM-dd");//2022-04-30LoginTime = Convert.ToDateTime(LoginDateTime).ToString("HH:mm:ss");//13:32:13//从属性中读数据UserID = eventInstance.Properties[0].Value.ToString().Substring(3).ToUpper();//A0236602ConnectedSecond = Convert.ToInt32(eventInstance.Properties[6].Value);//显示在程序界面的内容Console.WriteLine("UserID: {0}", UserID);Console.WriteLine("ConnectSeconds: {0}", ConnectedSecond);Console.WriteLine("LoginTimeFull: {0}", LoginDateTime);Console.WriteLine("LoginDate: {0}", LoginDate);Console.WriteLine("LoginTime: {0}", LoginTime);//插入DB的部分...}}}Console.WriteLine("-----------------------------------------------------");Console.WriteLine("TotalRecord: {0}, 303Type Record:{1}, Insert OK Record:{2}", TotalCount, Count303Type, InsertCount);Console.WriteLine("-----------------------------------------------------");//参数文件中读取备份路径string LogFileBackupPath = ConfigurationManager.AppSettings["LogBackupPath"].ToString();//如果不存在就创建file文件夹if (Directory.Exists(LogFileBackupPath) == false){Directory.CreateDirectory(LogFileBackupPath);}//产生一个随机数Random random = new Random(System.Environment.TickCount);int randomNumber = random.Next(1001, 9999);//备份文件路径和名称           string LogFileBackupFile = LogFileBackupPath + "\\" + DateTime.Now.ToString("yyyyMMddHHmmss")+ randomNumber + ".evtx";//源文件路径和名称string LogSourceLocation = SourceLocation;//移动到备份路径,不能用Move,因为文件在使用中File.Copy(LogSourceLocation, LogFileBackupFile);//如果要压缩则可以用下面的方法LogFileBackupFile = LogFileBackupPath + "\\" + DateTime.Now.ToString("yyyyMMddHHmmss")+ randomNumber + ".zip";ZipHelper.CreateZip(LogSourceLocation, LogFileBackupFile);//处理完毕后,窗口自动关闭//如果不想自动关闭,可以增加下面的两行代码Console.WriteLine("Press [Enter] To Exist");Console.ReadLine();
}

压缩Helper

也很简单,把这个加入项目即可,但需要:ICSharpCode.SharpZipLib.dll

 public class ZipHelper{/// <summary>/// 压缩文件/// </summary>/// <param name="sourceFilePath"></param>/// <param name="destinationZipFilePath"></param>public static void CreateZip(string sourceFilePath, string destinationZipFilePath){            ZipOutputStream zipStream = new ZipOutputStream(File.Create(destinationZipFilePath));zipStream.SetLevel(6);  // 压缩级别 0-9CreateSingleZipFile(sourceFilePath, zipStream);zipStream.Finish();zipStream.Close();}//压缩单个文件private static void CreateSingleZipFile(string sourceFile, ZipOutputStream zipStream){Crc32 crc = new Crc32();FileStream fileStream = File.OpenRead(sourceFile);byte[] buffer = new byte[fileStream.Length];fileStream.Read(buffer, 0, buffer.Length);string tempFile = sourceFile.Substring(sourceFile.LastIndexOf("\\") + 1);ZipEntry entry = new ZipEntry(tempFile);entry.DateTime = DateTime.Now;entry.Size = fileStream.Length;fileStream.Close();crc.Reset();crc.Update(buffer);entry.Crc = crc.Value;zipStream.PutNextEntry(entry);zipStream.Write(buffer, 0, buffer.Length);}/// <summary>/// 递归压缩文件/// </summary>/// <param name="sourceFilePath">待压缩的文件或文件夹路径</param>/// <param name="zipStream">打包结果的zip文件路径(类似 D:\WorkSpace\a.zip),全路径包括文件名和.zip扩展名</param>/// <param name="staticFile"></param>private static void CreateZipFiles(string sourceFilePath, ZipOutputStream zipStream){Crc32 crc = new Crc32();string[] filesArray = Directory.GetFileSystemEntries(sourceFilePath);foreach (string file in filesArray){if (Directory.Exists(file))                     //如果当前是文件夹,递归{CreateZipFiles(file, zipStream);}else                                            //如果是文件,开始压缩{FileStream fileStream = File.OpenRead(file);byte[] buffer = new byte[fileStream.Length];fileStream.Read(buffer, 0, buffer.Length);string tempFile = file.Substring(sourceFilePath.LastIndexOf("\\") + 1);ZipEntry entry = new ZipEntry(tempFile);entry.DateTime = DateTime.Now;entry.Size = fileStream.Length;fileStream.Close();crc.Reset();crc.Update(buffer);entry.Crc = crc.Value;zipStream.PutNextEntry(entry);zipStream.Write(buffer, 0, buffer.Length);}}}}

c# 读取Windows EventLog相关推荐

  1. Windows如何读取Linux,Linux下读取Windows注册表

    原本以为Linux下读取Windows的注册表是个异想天开.无法实现的想法,忽然发现了老外写的一段小文章 http://www.linuxidc.com/Linux/2011-04/34100p2.h ...

  2. java web 中 读取windows图标并显示

    java web中读取windows对应文件名的 系统图标 ....显示 1.获取系统图标工具类 package utils;  import java.awt.Graphics;  import j ...

  3. Ubuntu安装过程中出现“没有定义根文件系统”,Ubuntu安装过程中无法读取Windows分区

    最近在使用Wubi安装Ubuntu 12.04.2 LTS的过程中,在重启进入Ubuntu安装界面时,弹出"没有定义根文件系统"的通知,在网上查询解决方案良久未找到合适的解决方法. ...

  4. 无法打开计算机上的event log服务,win 2008 r2无法启动(Task Scheduler和windows eventlog 服务...

    Windows Server 2008 r2: 无法启动(Task Scheduler和windows eventlog 服务) =================================== ...

  5. logstash收集windows eventlog

    ==============================logstash收集windows eventlog=================================== windows下 ...

  6. 超详细:Java 读取 Windows 共享文件夹中的文件,并下载到本地电脑中

    目录 JCIFS 介绍 SMB协议 设置共享文件夹(这里我们选择有密码的方式进行共享) 是否设置密码 创建 smb 协议 测试 使用代码将文件夹里的文件下载到本地 项目常常需要有访问共享文件夹的需求, ...

  7. 【kali】28 提权——读取windows本地密码:pwddump、WCE、fgdump、mimikatz

    这里写自定义目录标题 一. 抓包嗅探 二. 键盘记录本地密码 三. 查看本地缓存密码 1. 浏览器查看密码 2. 密码恢复工具 3. 使用 Pwdump 查看 windows 本地登录密码 4. 了解 ...

  8. Linux读取windows光盘,如何从Windows,Mac和Linux上的光盘创建ISO文件

    ISO文件是光盘映像 - 捆绑在单个文件中的CD或DVD的完整映像. 然后,该文件可以"装载"并作为虚拟CD或DVD可用,允许您将物理光盘转换为虚拟光盘. 请注意,一些DRM复制保 ...

  9. python环境变量值_如何在python中读取Windows环境变量值?

    尝试使用以下内容: os.getenv('MyVar') os.getenv(varname[, value]) Return the value of the environment variabl ...

最新文章

  1. git stash 拉去_git操作命令符
  2. 33篇顶会论文如何做到?北大施柏鑫:论文投稿到接收,不可不知的关键环节...
  3. select * from table with(nolock)
  4. 最新!中国天气网api接口调用,key获取方式,数据请求秘钥获取,城市id获取方法
  5. Java Web使用数据库连接池
  6. C++const类型的引用参数
  7. matlab直流电机双闭环控制系统设计,基于MATLAB的直流电机双闭环调速系统设计毕业论文.doc...
  8. jQuery--基本选择器
  9. unity3d 自动变化大小_自动做游戏(1),自动生成人物侧面图
  10. 复变函数与积分变换小结
  11. stc15f2k60f2单片机定时器_8 STC15F2K60S2单片机的定时器计数器 例题
  12. Excel如何将两列内容合并到一列并在中间添加符号
  13. Java自动生成5道100以内的加减法口算题
  14. phalapi可以依赖注入么_PhalApi 2.7 开发快速上手
  15. 关于C#如何引用Microsoft.Office.Interop.Excel
  16. csdn 群发 粉丝 博文 博客
  17. JavaScript 内存详解 分析指南
  18. 8万条数据告诉你:跟着大股东和高管买他家股票,能赚钱吗?【邢不行|量化小讲堂系列60-实战篇】
  19. 活动预告+征集讲师和话题:iOS/Android DevCamp | CMDN CLUB移动开发者俱乐部清凉夏日嘉年华 | 7月27日 7月28日 | 北京...
  20. 日本西历和和历的转换(转)

热门文章

  1. 【NDK】【019】NDK使用cmath库
  2. Linux环境下实现excel文件转pdf并且实现优化
  3. Python使用Windows剪切板
  4. 【Python 基础】网络编程 - Python写一个简单的HTTP服务端和客户端,实现Client/Server交互
  5. 短视频创作应该注意什么问题?
  6. 论文阅读——ssFPN
  7. HDU 3338 Kakuro Extension
  8. 选择篇(013)-下面代码的输出是什么?
  9. 计算机跟广告设计那个学容易,学广告设计与制作用什么笔记本电脑好?
  10. 织梦mysql安装教程_新手教程:DedeCmsV5.7 SP1详细安装步骤(2)