Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 
(연관된 글이 1개 있습니다.)

C# - Environment.OSVersion의 문제점 및 윈도우 운영체제의 버전을 구하는 다양한 방법

아래의 글에서도 잘 설명하고 있지만,

WPF - 당신의 Environment.OSVersion은 거짓말을 하고 있다
; https://blog.gilbok.com/wpf-your-environment-dot-osversion-is-a-lier/

Windows 10/2019에서조차 Environment.OSVersion.Version은 6.2.9200.0을 반환합니다.

Console.WriteLine(Environment.OSVersion.Version);
// Windows 10 / Server 2019 - 6.2.9200.0
// Windows Server 2016 - 6.2.9200.0
// Windows Server 2012 R2 - 6.2.9200.0
// Windows Server 2008 R2 - 6.1.7601.65536

이 문제를 해결하기 위해 "Application Manifest File (Windows only)" 유형의 파일을 추가하면 다음과 같은 내용을 갖는 app.manifest 파일이 추가되고,

<?xml version="1.0" encoding="utf-8"?>
<assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1">
  <assemblyIdentity version="1.0.0.0" name="MyApplication.app"/>
  <trustInfo xmlns="urn:schemas-microsoft-com:asm.v2">
    <security>
      <requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3">
        <!-- UAC Manifest Options
             If you want to change the Windows User Account Control level replace the 
             requestedExecutionLevel node with one of the following.

        <requestedExecutionLevel  level="asInvoker" uiAccess="false" />
        <requestedExecutionLevel  level="requireAdministrator" uiAccess="false" />
        <requestedExecutionLevel  level="highestAvailable" uiAccess="false" />

            Specifying requestedExecutionLevel element will disable file and registry virtualization. 
            Remove this element if your application requires this virtualization for backwards
            compatibility.
        -->
        <requestedExecutionLevel level="asInvoker" uiAccess="false" />
      </requestedPrivileges>
    </security>
  </trustInfo>

  <compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1">
    <application>
      <!-- A list of the Windows versions that this application has been tested on
           and is designed to work with. Uncomment the appropriate elements
           and Windows will automatically select the most compatible environment. -->

      <!-- Windows Vista -->
      <!--<supportedOS Id="{e2011457-1546-43c5-a5fe-008deee3d3f0}" />-->

      <!-- Windows 7 -->
      <!--<supportedOS Id="{35138b9a-5d96-4fbd-8e2d-a2440225f93a}" />-->

      <!-- Windows 8 -->
      <!--<supportedOS Id="{4a2f28e3-53b9-4441-ba9c-d69d4a4a6e38}" />-->

      <!-- Windows 8.1 -->
      <!--<supportedOS Id="{1f676c76-80e1-4239-95bb-83d0f6d0da78}" />-->

      <!-- Windows 10 -->
      <!--<supportedOS Id="{8e0f7a12-bfb3-4fe8-b9a5-48fd50a15a9a}" />-->

    </application>
  </compatibility>

  <!-- Indicates that the application is DPI-aware and will not be automatically scaled by Windows at higher
       DPIs. Windows Presentation Foundation (WPF) applications are automatically DPI-aware and do not need 
       to opt in. Windows Forms applications targeting .NET Framework 4.6 that opt into this setting, should 
       also set the 'EnableWindowsFormsHighDpiAutoResizing' setting to 'true' in their app.config. -->
  <!--
  <application xmlns="urn:schemas-microsoft-com:asm.v3">
    <windowsSettings>
      <dpiAware xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings">true</dpiAware>
    </windowsSettings>
  </application>
  -->

  <!-- Enable themes for Windows common controls and dialogs (Windows XP and later) -->
  <!--
  <dependency>
    <dependentAssembly>
      <assemblyIdentity
          type="win32"
          name="Microsoft.Windows.Common-Controls"
          version="6.0.0.0"
          processorArchitecture="*"
          publicKeyToken="6595b64144ccf1df"
          language="*"
        />
    </dependentAssembly>
  </dependency>
  -->

</assembly>

이중에서 compatibility 영역을 해당 닷넷 애플리케이션의 요구에 따라 적절하게 주석을 해제하면 됩니다.

<compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1">
    <application>
        <!-- Windows Vista -->
        <supportedOS Id="{e2011457-1546-43c5-a5fe-008deee3d3f0}" />

        <!-- Windows 7 -->
        <supportedOS Id="{35138b9a-5d96-4fbd-8e2d-a2440225f93a}" />

        <!-- Windows 8 -->
        <supportedOS Id="{4a2f28e3-53b9-4441-ba9c-d69d4a4a6e38}" />

        <!-- Windows 8.1 -->
        <supportedOS Id="{1f676c76-80e1-4239-95bb-83d0f6d0da78}" />

        <!-- Windows 10 -->
        <supportedOS Id="{8e0f7a12-bfb3-4fe8-b9a5-48fd50a15a9a}" />

    </application>
</compatibility>

이후 다시 빌드하면 다음과 같이 정상적으로 버전을 가져옵니다.

Console.WriteLine(Environment.OSVersion.Version);
// Windows 10 20H2 - 10.0.19042.0
// Windows Server 2019 - 10.0.17763.0    
// Windows Server 2016 - 10.0.14393.0
// Windows Server 2012 R2 - 6.3.9600.0
// Windows Server 2008 R2 - 6.1.7601.65536




그런데, 만약 app.manifest를 임의로 추가할 수 없는 라이브러리에서의 코드라면 어떻게 해야 할까요?

How to get Windows Version - as in "Windows 10, version 1607"?
; https://stackoverflow.com/questions/39778525/how-to-get-windows-version-as-in-windows-10-version-1607

위의 글을 보면 추가로 고려할 수 있는 2가지 방법을 소개합니다.

  1. 레지스트리 키 이용 - HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ReleaseId
  2. WMIN 이용 - "Win32_OperatingSystem" / "Version"

여기서 레지스트리의 경우 Windows 10의 YYMM 표기로 된 버전을 반환합니다.

Windows 10 20H2 버전의 경우 - 2009
Windows Server 2019 - 1809
Windows Server 2016 - 1607
Windows Server 2012 R2 - (empty)
Windows Server 2008 R2 - (empty)

반면 WMI의 경우 Environment.OSVersion.Version과 결과는 유사하지만 3자리 버전 번호를 반환한다는 차이가 있습니다.

Windows 10 20H2 버전의 경우 - 10.0.19042
Windows Server 2019 - 10.0.17763
Windows Server 2016 - 10.0.14393
Windows Server 2012 R2 - 6.3.9600
Windows Server 2008 R2 - 6.1.7601

한 가지 단점이라면 WMI의 특성상 최초 호출 시 다소 느리다는 점을 염두에 두어야 합니다.




만약, 버전을 구하는 것이 아닌, 특정 버전을 만족하는지에 대한 정보만 필요한 것이라면 P/Invoke를 활용하는 것도 방법일 수 있습니다.

IsWindowsVersionOrGreater function (versionhelpers.h)
; https://learn.microsoft.com/en-us/windows/win32/api/versionhelpers/nf-versionhelpers-iswindowsversionorgreater

단지 이 함수가 내부적으로는 versionhelpers.h에 다음과 같이 VerifyVersionInfo를 사용하는 함수로 정의되어 있으므로,

VERSIONHELPERAPI
IsWindowsVersionOrGreater(WORD wMajorVersion, WORD wMinorVersion, WORD wServicePackMajor)
{
    OSVERSIONINFOEXW osvi = { sizeof(osvi), 0, 0, 0, 0, {0}, 0, 0 };
    DWORDLONG        const dwlConditionMask = VerSetConditionMask(
        VerSetConditionMask(
        VerSetConditionMask(
            0, VER_MAJORVERSION, VER_GREATER_EQUAL),
               VER_MINORVERSION, VER_GREATER_EQUAL),
               VER_SERVICEPACKMAJOR, VER_GREATER_EQUAL);

    osvi.dwMajorVersion = wMajorVersion;
    osvi.dwMinorVersion = wMinorVersion;
    osvi.wServicePackMajor = wServicePackMajor;

    return VerifyVersionInfoW(&osvi, VER_MAJORVERSION | VER_MINORVERSION | VER_SERVICEPACKMAJOR, dwlConditionMask) != FALSE;
}

결국 저 코드를 구현하는 C# 코드를 작성해야 합니다.

[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
extern static bool VerifyVersionInfoW(ref OSVERSIONINFOEXW lpVersionInformation, int dwTypeMask, ulong dwlConditionMask);

[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
extern static ulong VerSetConditionMask(ulong conditionMask, int typeMask, byte condition);

static bool IsWindowsVersionOrGreater(ushort wMajorVersion, ushort wMinorVersion, ushort wServicePackMajor)
{
    OSVERSIONINFOEXW osvi = new OSVERSIONINFOEXW();
    osvi.dwOSVersionInfoSize = Marshal.SizeOf(osvi);

    ulong dwlConditionMask = VerSetConditionMask(
        VerSetConditionMask(
        VerSetConditionMask(
            0, VER_MAJORVERSION, (byte)VER_GREATER_EQUAL),
                VER_MINORVERSION, (byte)VER_GREATER_EQUAL),
                VER_SERVICEPACKMAJOR, (byte)VER_GREATER_EQUAL);

    osvi.dwMajorVersion = wMajorVersion;
    osvi.dwMinorVersion = wMinorVersion;
    osvi.wServicePackMajor = wServicePackMajor;

    return VerifyVersionInfoW(ref osvi, VER_MAJORVERSION | VER_MINORVERSION | VER_SERVICEPACKMAJOR, dwlConditionMask) != false;
}

그런데 "IsWindowsVersionOrGreater" 함수 도움말에는 나오지 않지만 저 코드가 동작하려면 app.manifest를 필요로 합니다. (유사하게 IsWindows10OrGreater 함수의 도움말에는 manifest가 필요하다는 설명이 있습니다.) 즉, 저걸 사용하느니 Environment.OSVersion으로 구현하는 것이 차라리 낫습니다.

게다가 위의 구현은 우리가 기대했던 버전 정보에 따른 결과를 반환하지도 않습니다.

Console.WriteLine($">= Windows 8: {IsWindows8OrGreater()}");
Console.WriteLine($">= Windows 10: {IsWindows10OrGreater()}"); // if without manifest, false
Console.WriteLine($">= 10.0.17063: {IsWindowsVersionOrGreater(10, 0, 17063)}"); // always false
Console.WriteLine($">= 10.0.19042: {IsWindowsVersionOrGreater(10, 0, 19042)}"); // always false
Console.WriteLine($">= 10.0.20000: {IsWindowsVersionOrGreater(10, 0, 20000)}"); // always false

/* 출력 결과 Windows 10 20H2에서 테스트
>= Windows 8: True
>= Windows 10: True
>= 10.0.17063: False
>= 10.0.19042: False
>= 10.0.20000: False
*/

static bool IsWindows8OrGreater()
{
    return IsWindowsVersionOrGreater(6, 2, 0);
}

static bool IsWindows10OrGreater()
{
    return IsWindowsVersionOrGreater(10, 0, 0);
}

이유를 알 수 없지만, versionhelpers.h에 담고 있는 C/C++ 코드가 이미 잘못된 부분이 있는데요, 우리가 알고 있는 3번째 버전 정보 - 예를 들어 "10.0.19042.0"에서 19042는 ServicePack 번호가 아닌 Build 번호이기 때문에 해당 코드를 다음과 같이 변경해야 합니다.

static bool IsWindowsVersionOrGreater(ushort wMajorVersion, ushort wMinorVersion, ushort wBuildVersion)
{
    OSVERSIONINFOEXW osvi = new OSVERSIONINFOEXW();
    osvi.dwOSVersionInfoSize = Marshal.SizeOf(osvi);

    ulong dwlConditionMask = VerSetConditionMask(
        VerSetConditionMask(
        VerSetConditionMask(
            0, VER_MAJORVERSION, (byte)VER_GREATER_EQUAL),
                VER_MINORVERSION, (byte)VER_GREATER_EQUAL),
                VER_BUILDNUMBER, (byte)VER_GREATER_EQUAL);

    osvi.dwMajorVersion = wMajorVersion;
    osvi.dwMinorVersion = wMinorVersion;
    osvi.dwBuildNumber = wBuildVersion;

    return VerifyVersionInfoW(ref osvi, VER_MAJORVERSION | VER_MINORVERSION | VER_BUILDNUMBER, dwlConditionMask) != false;
}

Console.WriteLine($">= Windows 8: {IsWindows8OrGreater()}");
Console.WriteLine($">= Windows 10: {IsWindows10OrGreater()}"); 
Console.WriteLine($">= 10.0.17063: {IsWindowsVersionOrGreater(10, 0, 17063)}");
Console.WriteLine($">= 10.0.19042: {IsWindowsVersionOrGreater(10, 0, 19042)}");
Console.WriteLine($">= 10.0.20000: {IsWindowsVersionOrGreater(10, 0, 20000)}");

/* 출력 결과 Windows 10 20H2에서 테스트
>= Windows 8: True
>= Windows 10: True
>= 10.0.17063: True
>= 10.0.19042: True
>= 10.0.20000: False
*/




마지막으로 ntdll.dll에서 제공하는 RtlGetVersion 함수를 보겠습니다.

RtlGetVersion function (wdm.h)
; https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/wdm/nf-wdm-rtlgetversion

문서를 보면 "Minimum supported client"가 Windows 2000이기 때문에 사실상 현재 모든 운영체제에서 호출 가능한 함수입니다. 그리고 출력 결과도 WMI의 것과 완전히 같으며 app.manifest 없이도 잘 동작합니다. 단지 SDK 레벨에서 숨겨진 함수라는 점을 제외한다면 현재 닷넷 라이브러리 수준에서 사용할 수 있는 가장 최선의 후보가 RtlGetVersion입니다.

[DllImport("ntdll.dll", CharSet = CharSet.Auto)]
extern static int RtlGetVersion(ref OSVERSIONINFOEXW lpVersionInformation);

Console.WriteLine($"RtlGetVersion: {GetRtlVersion()}");            

static Version GetRtlVersion()
{
    OSVERSIONINFOEXW info = new OSVERSIONINFOEXW();
    info.dwOSVersionInfoSize = Marshal.SizeOf(info);

    RtlGetVersion(ref info);

    return new Version(info.dwMajorVersion, info.dwMinorVersion, info.dwBuildNumber);
}

이 글의 예제 코드는 다음의 github repo에 있습니다.

DotNetSamples/WinConsole/OSVersionInfo
; https://github.com/stjeong/DotNetSamples/tree/master/WinConsole/OSVersionInfo




그나저나, 테스트하면서 알게 된 이상한 점이 하나 있는데요, w3wp.exe에서 호스팅하는 ASP.NET 응용 프로그램에서 Environment.OSVersion.Version을 구하면 정상적으로 운영체제 버전이 반환됩니다. 왜 그것이 이상하냐면, 바로 w3wp.exe는 manifest 파일을 포함하고 있지 않기 때문입니다.

도대체 w3wp.exe에는 어떤 마법이 숨겨져 있는 걸까요? 혹시 아시는 분은 덧글 부탁드립니다. ^^

이렇게 혼란스러운 와중에 한 가지 좋은 소식이라면, .NET Core의 경우 app.manifest 파일 없이 Environment.OSVersion.Version은 RtlGetVersion처럼 동작합니다.




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]

[연관 글]






[최초 등록일: ]
[최종 수정일: 10/31/2023]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 



2021-09-30 10시31분
[클락] https://learn.microsoft.com/ko-kr/dotnet/core/compatibility/core-libraries/5.0/environment-osversion-returns-correct-version
Environment.OSVersion에서 올바른 운영 체제 버전이 반환됨

https://learn.microsoft.com/ko-kr/dotnet/api/system.environment.osversion?view=net-5.0
에 나와 있듯이 .NET 5.0에서 변경된 것 같습니다.
그전 버전에는 GetVersionEx와 같은 문제가 있다고 합니다.

"https://github.com/dotnet/runtime" 소스 코드에서 확인했는데, Environment.OSVersion 속성 초기화할 때 GetOSVersion() 메서드 내에서 RtlGetVersionEx 함수를 사용해 구현하고 있습니다.
[guest]

1  2  3  4  5  6  7  8  9  10  11  [12]  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13329정성태4/24/20233706Windows: 246. Win32 C/C++ - 직접 띄운 대화창 템플릿을 위한 Modal 메시지 루프 생성파일 다운로드1
13328정성태4/19/20233379VS.NET IDE: 184. Visual Studio - Fine Code Coverage에서 동작하지 않는 Fake/Shim 테스트
13327정성태4/19/20233794VS.NET IDE: 183. C# - .NET Core/5+ 환경에서 Fakes를 이용한 단위 테스트 방법
13326정성태4/18/20235205.NET Framework: 2109. C# - 닷넷 응용 프로그램에서 SQLite 사용 (System.Data.SQLite) [1]파일 다운로드1
13325정성태4/18/20234505스크립트: 48. 파이썬 - PostgreSQL의 with 문을 사용한 경우 연결 개체 누수
13324정성태4/17/20234319.NET Framework: 2108. C# - Octave의 "save -binary ..."로 생성한 바이너리 파일 분석파일 다운로드1
13323정성태4/16/20234260개발 환경 구성: 677. Octave에서 Excel read/write를 위한 io 패키지 설치
13322정성태4/15/20235038VS.NET IDE: 182. Visual Studio - 32비트로만 빌드된 ActiveX와 작업해야 한다면?
13321정성태4/14/20233827개발 환경 구성: 676. WSL/Linux Octave - Python 스크립트 연동
13320정성태4/13/20233806개발 환경 구성: 675. Windows Octave 8.1.0 - Python 스크립트 연동
13319정성태4/12/20234291개발 환경 구성: 674. WSL 2 환경에서 GNU Octave 설치
13318정성태4/11/20234114개발 환경 구성: 673. JetBrains IDE에서 "Squash Commits..." 메뉴가 비활성화된 경우
13317정성태4/11/20234228오류 유형: 855. WSL 2 Ubuntu 20.04 - error: cannot communicate with server: Post http://localhost/v2/snaps/...
13316정성태4/10/20233553오류 유형: 854. docker-compose 시 "json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)" 오류 발생
13315정성태4/10/20233750Windows: 245. Win32 - 시간 만료를 갖는 컨텍스트 메뉴와 윈도우 메시지의 영역별 정의파일 다운로드1
13314정성태4/9/20233828개발 환경 구성: 672. DosBox를 이용한 Turbo C, Windows 3.1 설치
13313정성태4/9/20233911개발 환경 구성: 671. Hyper-V VM에 Turbo C 2.0 설치 [2]
13312정성태4/8/20233933Windows: 244. Win32 - 시간 만료를 갖는 MessageBox 대화창 구현 (개선된 버전)파일 다운로드1
13311정성태4/7/20234442C/C++: 163. Visual Studio 2022 - DirectShow 예제 컴파일(WAV Dest)
13310정성태4/6/20234021C/C++: 162. Visual Studio - /NODEFAULTLIB 옵션 설정 후 수동으로 추가해야 할 library
13309정성태4/5/20234206.NET Framework: 2107. .NET 6+ FileStream의 구조 변화
13308정성태4/4/20234098스크립트: 47. 파이썬의 time.time() 실숫값을 GoLang / C#에서 사용하는 방법
13307정성태4/4/20233868.NET Framework: 2106. C# - .NET Core/5+ 환경의 Windows Forms 응용 프로그램에서 HINSTANCE 구하는 방법
13306정성태4/3/20233668Windows: 243. Win32 - 윈도우(cbWndExtra) 및 윈도우 클래스(cbClsExtra) 저장소 사용 방법
13305정성태4/1/20234032Windows: 242. Win32 - 시간 만료를 갖는 MessageBox 대화창 구현 (쉬운 버전)파일 다운로드1
13304정성태3/31/20234387VS.NET IDE: 181. Visual Studio - C/C++ 프로젝트에 application manifest 적용하는 방법
1  2  3  4  5  6  7  8  9  10  11  [12]  13  14  15  ...