.NET Standard 2.0如何实现获取PC上次启动时间?
在.NET Standard 2.0中获取PC上次启动时间的方案
可以在.NET Standard 2.0中实现该功能,以下是两种可行方案:
方案一:基于WMI实现(与原代码逻辑一致)
.NET Standard 2.0本身未内置System.Management相关类型,但可通过安装System.Management NuGet包复用原代码逻辑。
安装包命令:
Install-Package System.Management
实现代码(与原代码基本一致):
using System; using System.Management; public static DateTime? GetLastBootTime() { DateTime? dtBootTime = null; SelectQuery query = new SelectQuery(@"SELECT LastBootUpTime FROM Win32_OperatingSystem WHERE Primary='true'"); ManagementObjectSearcher searcher = new ManagementObjectSearcher(query); foreach (ManagementObject mo in searcher.Get()) { dtBootTime = ManagementDateTimeConverter.ToDateTime(mo.Properties["LastBootUpTime"].Value.ToString()); } return dtBootTime; }
注意:该方案依赖WMI技术,仅适用于Windows平台。
方案二:通过P/Invoke调用Windows原生API
若不想依赖额外NuGet包,可直接调用Windows系统的GetTickCount64API实现,无需封装依赖:
using System; using System.Runtime.InteropServices; public static DateTime? GetLastBootTime() { // 仅在Windows平台执行逻辑 if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { return null; } long tickCount = GetTickCount64(); // 基于当前时间倒推系统启动时间 return DateTime.UtcNow.AddMilliseconds(-tickCount).ToLocalTime(); } [DllImport("kernel32.dll")] private static extern long GetTickCount64();
注意:该方案同样仅支持Windows平台,无需额外依赖包,性能更优。
额外说明
- 上述两种方案均仅适配Windows平台,若共享类库需要跨Linux、macOS等非Windows环境,需针对对应系统编写平台专属的获取逻辑。
- 若需跨平台支持,可结合
RuntimeInformation.IsOSPlatform做分支判断,实现多平台兼容。
内容的提问来源于stack exchange,提问作者Smith5727
相关产品推荐
相关产品推荐

