编程语言
首页 > 编程语言> > 使用C#在一天中获取服务器重启计数?

使用C#在一天中获取服务器重启计数?

作者:互联网

是否可以使用C#获得一段时间内服务器重新启动的次数?

我看过这篇文章,它正在获取Windows的最后关闭时间Get the date-time of last windows shutdown event using .NET

有什么建议吗?

解决方法:

您是否考虑过阅读服务器的事件日志?

“ USER32”系统事件源记录了关闭.

从我阅读的内容来看,您似乎也应该能够以编程方式读取远程计算机的事件日志(See How to manage event logs using Visual C# .NET or Visual C# 2005)

编辑

以下控制台应用程序将在查询远程计算机上的偶数日志中查找USER32类型.

您所要做的就是插入日期/时间比较并添加服务器名称.它有点粗糙并且准备好了,但是我敢肯定,如果您愿意的话,您可以对其进行一些美化.

using System;
using System.Diagnostics;

namespace ReadEventLog
{
    class Program
    {
        static void Main(string[] args)
        {

            string logType = "System";

            //use this if your are are running the app on the server
            //EventLog ev = new EventLog(logType, System.Environment.MachineName);    

            //use this if you are running the app remotely
            EventLog ev = new EventLog(logType, "[youservername]");

            if (ev.Entries.Count <= 0)
                Console.WriteLine("No Event Logs in the Log :" + logType);

            // Loop through the event log records. 
            for (int i = ev.Entries.Count - 1; i >= 0; i--)
            {
                EventLogEntry CurrentEntry = ev.Entries[i];

                //use DateTime type to compare on CurrentEntry.TimeGenerated
                DateTime dt = DateTime.Now;
                TimeSpan ts = dt.Subtract( CurrentEntry.TimeGenerated);
                int hours = (ts.Days * 24) + ts.Hours;

                if (CurrentEntry.Source.ToUpper() == "USER32")
                {
                    Console.WriteLine("Time Generated:" + CurrentEntry.TimeGenerated);
                    Console.WriteLine("Hours ago:" + hours);
                    Console.WriteLine("Event ID : " + CurrentEntry.InstanceId);
                    Console.WriteLine("Entry Type : " + CurrentEntry.EntryType.ToString());
                    Console.WriteLine("Message :  " + CurrentEntry.Message + "\n");
                }
            }
            ev.Close();
        }
    }
}

标签:windows-services,c
来源: https://codeday.me/bug/20191208/2090770.html