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)
13356정성태5/15/20233889DDK: 10. Device Driver 테스트 설치 관련 오류 (Code 37, Code 31) 및 인증서 관련 정리
13355정성태5/12/20233826.NET Framework: 2123. C# - Semantic Kernel의 ChatGPT 대화 구현 [1]파일 다운로드1
13354정성태5/12/20234077.NET Framework: 2122. C# - "Use Unicode UTF-8 for worldwide language support" 설정을 한 경우, 한글 입력이 '\0' 문자로 처리
13352정성태5/12/20233695.NET Framework: 2121. C# - Semantic Kernel의 대화 문맥 유지파일 다운로드1
13351정성태5/11/20234202VS.NET IDE: 185. Visual Studio - 원격 Docker container 내에 실행 중인 응용 프로그램에 대한 디버깅 [1]
13350정성태5/11/20233475오류 유형: 859. Windows Date and Time - Unable to continue. You do not have permission to perform this task
13349정성태5/11/20233776.NET Framework: 2120. C# - Semantic Kernel의 Skill과 Function 사용 예제파일 다운로드1
13348정성태5/10/20233682.NET Framework: 2119. C# - Semantic Kernel의 "Basic Loading of the Kernel" 예제
13347정성태5/10/20234074.NET Framework: 2118. C# - Semantic Kernel의 Prompt chaining 예제파일 다운로드1
13346정성태5/10/20233899오류 유형: 858. RDP 원격 환경과 로컬 PC 간의 Ctrl+C, Ctrl+V 복사가 안 되는 문제
13345정성태5/9/20235276.NET Framework: 2117. C# - (OpenAI 기반의) Microsoft Semantic Kernel을 이용한 자연어 처리 [1]파일 다운로드1
13344정성태5/9/20236483.NET Framework: 2116. C# - OpenAI API 사용 - 지원 모델 목록 [1]파일 다운로드1
13343정성태5/9/20234354디버깅 기술: 192. Windbg - Hyper-V VM으로 이더넷 원격 디버깅 연결하는 방법
13342정성태5/8/20234268.NET Framework: 2115. System.Text.Json의 역직렬화 시 필드/속성 주의
13341정성태5/8/20234000닷넷: 2114. C# 12 - 모든 형식의 별칭(Using aliases for any type)
13340정성태5/8/20234074오류 유형: 857. Microsoft.Data.SqlClient.SqlException - 0x80131904
13339정성태5/6/20234736닷넷: 2113. C# 12 - 기본 생성자(Primary Constructors)
13338정성태5/6/20234255닷넷: 2112. C# 12 - 기본 람다 매개 변수파일 다운로드1
13337정성태5/5/20234762Linux: 59. dockerfile - docker exec로 container에 접속 시 자동으로 실행되는 코드 적용
13336정성태5/4/20234569.NET Framework: 2111. C# - 바이너리 출력 디렉터리와 연관된 csproj 설정
13335정성태4/30/20234669.NET Framework: 2110. C# - FFmpeg.AutoGen 라이브러리를 이용한 기본 프로젝트 구성 - Windows Forms파일 다운로드1
13334정성태4/29/20234301Windows: 250. Win32 C/C++ - Modal 메시지 루프 내에서 SetWindowsHookEx를 이용한 Thread 메시지 처리 방법
13333정성태4/28/20233746Windows: 249. Win32 C/C++ - 대화창 템플릿을 런타임에 코딩해서 사용파일 다운로드1
13332정성태4/27/20233845Windows: 248. Win32 C/C++ - 대화창을 위한 메시지 루프 사용자 정의파일 다운로드1
13331정성태4/27/20233850오류 유형: 856. dockerfile - 구 버전의 .NET Core 이미지 사용 시 apt update 오류
13330정성태4/26/20233493Windows: 247. Win32 C/C++ - CS_GLOBALCLASS 설명
1  2  3  4  5  6  7  8  9  10  [11]  12  13  14  15  ...