【以下回答由 ChatGPT 生成】
Environment.TickCount
返回的是从系统启动到现在所经过的毫秒数,并不是系统本次开机的时间。要获取系统本次开机的时间,可以使用System.Diagnostics
命名空间中的Process.StartTime
属性。
下面是使用C#获取系统本次开机时间的代码:
using System;
using System.Diagnostics;
class Program
{
static void Main(string[] args)
{
TimeSpan uptime = DateTime.Now - GetLastBootTime();
Console.WriteLine("本次开机时间:" + uptime.ToString());
}
static DateTime GetLastBootTime()
{
using (var process = new Process())
{
process.StartInfo.FileName = "cmd.exe";
process.StartInfo.Arguments = "/c systeminfo | find \"System Boot Time\"";
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.UseShellExecute = false;
process.StartInfo.CreateNoWindow = true;
process.Start();
string output = process.StandardOutput.ReadToEnd();
string bootTimeStr = output.Substring(output.IndexOf(':') + 2);
DateTime bootTime = DateTime.Parse(bootTimeStr);
process.WaitForExit();
return bootTime;
}
}
}
以上代码中,我们使用System.Diagnostics.Process
启动一个命令行进程,执行systeminfo
命令,并通过管道过滤出包含"System Boot Time"关键字的行。然后将输出结果解析为DateTime
类型的系统开机时间。
需要注意的是,此方法需要使用systeminfo
命令,因此要求代码运行在具有足够权限的环境中。
如果不能使用System.Diagnostics.Process
获取系统开机时间,我们可以通过使用Windows Management Instrumentation (WMI)查询Win32_OperatingSystem类来获取系统开机时间。以下是使用WMI获取系统开机时间的代码示例:
using System;
using System.Management;
class Program
{
static void Main(string[] args)
{
TimeSpan uptime = DateTime.Now - GetLastBootTime();
Console.WriteLine("本次开机时间:" + uptime.ToString());
}
static DateTime GetLastBootTime()
{
var scope = new ManagementScope("\\\\.\\root\\cimv2");
var query = new ObjectQuery("SELECT LastBootUpTime FROM Win32_OperatingSystem");
using (var searcher = new ManagementObjectSearcher(scope, query))
using (var results = searcher.Get())
{
foreach (var item in results)
{
var bootTimeStr = item["LastBootUpTime"].ToString();
var bootTime = ManagementDateTimeConverter.ToDateTime(bootTimeStr);
return bootTime;
}
}
throw new Exception("Unable to retrieve system boot time.");
}
}
以上代码使用WMI查询Win32_OperatingSystem类的LastBootUpTime
属性,将其转换为DateTime
类型的系统开机时间。
这两种方法都可以获取到系统本次开机的时间,选择合适的方法取决于具体的需求和运行环境。
如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^