细心的同学会发现,我们通过内置函数Environment.OSVersion
获取到的系统版本号会存在不同的系统版本,版本号是一样的情况。代替的方案可以通过windows api 来获取内置版本号。
实现方法比较简单,就不做描述,以下是完整可用的代码。
public class Win32
{
[DllImport("ntdll.dll", CharSet = CharSet.Auto)]
public static extern IntPtr RtlGetNtVersionNumbers(ref int dwMajor, ref int dwMinor, ref int dwBuildNumber);
}
public class EnvironmentEx
{
/// <summary>
/// 获取系统版本号
/// </summary>
public static string OSVersion
{
get
{
try
{
int dwMajor = 0, dwMinor = 0, dwBuildNumber = 0, buildNum = 0;
Win32.RtlGetNtVersionNumbers(ref dwMajor, ref dwMinor, ref dwBuildNumber);
if (dwBuildNumber != 0)
{
var bytes = ByteConvert.IntToBytes(dwBuildNumber);
buildNum = ByteConvert.BytesToInt(new byte[] { bytes[0], bytes[1], 0, 0 }, 0);
}
return $"{dwMajor}.{dwMinor}.{buildNum}";
}
catch (Exception)
{
return Environment.OSVersion.ToString();
}
}
}
}
public class ByteConvert
{
public static int BytesToInt(byte[] src, int offset)
{
if (src == null) return 0;
int value;
value = (src[offset] & 0xFF)
| ((src[offset + 1] & 0xFF) << 8)
| ((src[offset + 2] & 0xFF) << 16)
| ((src[offset + 3] & 0xFF) << 24);
return value;
}
public static byte[] IntToBytes(int value)
{
byte[] src = new byte[4];
src[3] = (byte)((value >> 24) & 0xFF);
src[2] = (byte)((value >> 16) & 0xFF);
src[1] = (byte)((value >> 8) & 0xFF);//高8位
src[0] = (byte)(value & 0xFF);//低位
return src;
}
}
标签:src,正确,版本号,获取,int,0xFF,ref,public
From: https://blog.csdn.net/qq_22933729/article/details/144164865