C#で実行中のWindowsのバージョンを判定する

土曜日 , 26, 8月 2023 Leave a comment

C#で簡単に実行中のWindowsのバージョンがWindows 10かWindows 11かを判定する方法がないようなので、ユーティリティクラスを書いてみました。

System.Runtime.InteropServices.RuntimeInformationクラスOSDescriptionプロパティから実行中のOSについての情報を取得し、取得した文字列に正規表現をぶつけてバージョンとビルド番号よりWindowsのバージョン判定を行っています。

将来的にWindows 12のような新しいバージョンのWindowsがリリースされたときには手直しが必要になると思います。

//
// 実行中のWindowsのバージョンを判定するユーティリティ
//
// This software is distributed under the license of NYSL.
// http://www.kmonos.net/nysl/
//
//
using System; using System.Runtime.InteropServices; using System.Text.RegularExpressions; namespace com.ria_lab.Utils { public class EnvUtil { /// <summary> /// 実行中の環境がWIndows 11か判定する /// </summary> /// <returns>true: Windows 11 / false: Windows 11以外</returns> public static bool IsWindows11() { var desc = RuntimeInformation.OSDescription; var m = Regex.Match(desc, @"Microsoft Windows (\d{1,}\.\d{1,})\.(\d{1,})"); if (!m.Success) { return false; } var os = m.Groups[1].Value; var build = Convert.ToInt32(m.Groups[2].Value); // 22000~をWindows 10とみなす return os == "10.0" && build >= 22000; } /// <summary> /// 実行中の環境がWIndows 10か判定する /// </summary> /// <returns>true: Windows 10 / false: Windows 10以外</returns> public static bool IsWindows10() { var desc = RuntimeInformation.OSDescription; var m = Regex.Match(desc, @"Microsoft Windows (\d{1,}\.\d{1,})\.(\d{1,})"); if (!m.Success) { return false; } var os = m.Groups[1].Value; var build = Convert.ToInt32(m.Groups[2].Value); // 10240から22000のあいだをWindows 10とみなす // (Version 22H2 OS build 19045が最終ビルドになるはずだが突発的なビルド番号アップを見越して22000まで) return os == "10.0" && build >= 10240 && build < 22000; } } }

Windows 10とWindows 11で、System.EnvironmentクラスOSVersionプロパティSystem.Runtime.InteropServices.RuntimeInformationクラスOSDescriptionプロパティの実行結果を比較してみると下記のような結果になります。

Please give us your valuable comment

メールアドレスが公開されることはありません。 が付いている欄は必須項目です

このサイトはスパムを低減するために Akismet を使っています。コメントデータの処理方法の詳細はこちらをご覧ください