Getting server restart count in a day using c#?

2020-07-21 11:03发布

问题:

Is it possible to get the number of times a server gets restarted in a period of time using c#?

I have seen this post which is getting windows last shutdown time Get the date-time of last windows shutdown event using .NET

Any suggestion?

回答1:

Have you considered reading from the server's event log?

The 'USER32' system event source records shutdowns.

From what I've read it seem that you should be able to read a remote machine's event log programmatically as well (See How to manage event logs using Visual C# .NET or Visual C# 2005)

EDIT

The following console app will work on querying the even log on a remote machine for the USER32 Type.

All you have to do is plug in the date/time comparison and add your server name. Its a bit rough and ready, but I'm sure you can beautify it a bit if you want.

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();
        }
    }
}


回答2:

You could create a windows service and log the startup event. That way you will know how many times the service has started (and been shut down).