我需要在C#中开发一个程序,找出Windows启动或关闭的时间.
是否有一个日志文件,我可以阅读以了解Windows的启动和关闭时间?或者您有任何想法如何这样做?
编辑:
在Reed Copsey先生的帮助下,在这个问题下找到了最佳答案.
Uwe*_*eim 15
根据这篇文章,您可以使用WMI来获取上次启动日期/时间.
// define a select query
SelectQuery query =
new SelectQuery(@"SELECT LastBootUpTime FROM Win32_OperatingSystem
WHERE Primary='true'");
// create a new management object searcher and pass it
// the select query
ManagementObjectSearcher searcher =
new ManagementObjectSearcher(query);
// get the datetime value and set the local boot
// time variable to contain that value
foreach(ManagementObject mo in searcher.Get())
{
dtBootTime =
ManagementDateTimeConverter.ToDateTime(
mo.Properties["LastBootUpTime"].Value.ToString());
// display the start time and date
txtDate.Text = dtBootTime.ToLongDateString();
txtTime.Text = dtBootTime.ToLongTimeString();
}
Run Code Online (Sandbox Code Playgroud)
System.Environment.TickCount有 24.8 天的限制。
这是因为TickCount是包含在有符号 32 位值中的毫秒值。
Windows API 公开这两个函数:
GetTickCount- 返回 32 位值 - 从 Windows 2000 可用
GetTickCount64- 返回 64 位值 - 从 Vista/Windows Server 2008 可用
您可以这样使用 GetTickCount64:
using System.Runtime.InteropServices;
[DllImport("Kernel32.dll")]
static extern long GetTickCount64();
DateTime osStartTime = DateTime.Now - new TimeSpan(10000 * GetTickCount64());
Run Code Online (Sandbox Code Playgroud)
正如 Reed 指出的,您可以访问事件日志并查看它们的创建时间。AFAIK 没有针对系统启动/关闭的特定事件条目,但您可以查找通常由 Windows 启动/停止的服务。虽然使用这种方法意味着它不会是 100% 准确的,比如它是否崩溃或者它是手动启动/停止/重新启动的。我认为最准确的一个事件是 EventLog 服务启动/停止事件。
if (EventLog.Exists("System"))
{
var log = new EventLog("System", Environment.MachineName, "EventLog");
var entries = new EventLogEntry[log.Entries.Count];
log.Entries.CopyTo(entries, 0);
var startupTimes = entries.Where(x => x.InstanceId == 2147489653).Select(x => x.TimeGenerated);
var shutdownTimes = entries.Where(x => x.InstanceId == 2147489654).Select(x => x.TimeGenerated);
}
Run Code Online (Sandbox Code Playgroud)
编辑
原来有一个关闭事件。您可以替换 Linq 来获取它:
var shutdownEvents = entries.Where(x => x.InstanceId == 2147484722);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13240 次 |
| 最近记录: |