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)
13532정성태1/17/20242189닷넷: 2205. C# - SuperSimpleTcp 사용 시 주의할 점파일 다운로드1
13531정성태1/16/20242234닷넷: 2204. C# - TCP KeepAlive에 새로 추가된 Retry 옵션파일 다운로드1
13530정성태1/15/20242189닷넷: 2203. C# - Python과의 AES 암호화 연동파일 다운로드1
13529정성태1/15/20242049닷넷: 2202. C# - PublishAot의 glibc에 대한 정적 링킹하는 방법
13528정성태1/14/20242175Linux: 68. busybox 컨테이너에서 실행 가능한 C++, Go 프로그램 빌드
13527정성태1/14/20242106오류 유형: 892. Visual Studio - Failed to launch debug adapter. Additional information may be available in the output window.
13526정성태1/14/20242203닷넷: 2201. C# - Facebook 연동 / 사용자 탈퇴 처리 방법
13525정성태1/13/20242157오류 유형: 891. Visual Studio - Web Application을 실행하지 못하는 IISExpress
13524정성태1/12/20242219오류 유형: 890. 한국투자증권 KIS Developers OpenAPI - GW라우팅 중 오류가 발생했습니다.
13523정성태1/12/20242027오류 유형: 889. Visual Studio - error : A project with that name is already opened in the solution.
13522정성태1/11/20242188닷넷: 2200. C# - HttpClient.PostAsJsonAsync 호출 시 "Transfer-Encoding: chunked" 대신 "Content-Length" 헤더 처리
13521정성태1/11/20242254닷넷: 2199. C# - 한국투자증권 KIS Developers OpenAPI의 WebSocket Ping, Pong 처리
13520정성태1/10/20241999오류 유형: 888. C# - Unable to resolve service for type 'Microsoft.Extensions.ObjectPool.ObjectPool`....'
13519정성태1/10/20242092닷넷: 2198. C# - Reflection을 이용한 ClientWebSocket의 Ping 호출파일 다운로드1
13518정성태1/9/20242351닷넷: 2197. C# - ClientWebSocket의 Ping, Pong 처리
13517정성태1/8/20242197스크립트: 63. Python - 공개 패키지를 이용한 위성 이미지 생성 (pystac_client, odc.stac)
13516정성태1/7/20242301닷넷: 2196. IIS - AppPool의 "Disable Overlapped Recycle" 옵션의 부작용
13515정성태1/6/20242581닷넷: 2195. async 메서드 내에서 C# 7의 discard 구문 활용 사례 [1]
13514정성태1/5/20242254개발 환경 구성: 702. IIS - AppPool의 "Disable Overlapped Recycle" 옵션
13513정성태1/5/20242175닷넷: 2194. C# - WebActivatorEx / System.Web의 PreApplicationStartMethod 특성
13512정성태1/4/20242142개발 환경 구성: 701. IIS - w3wp.exe 프로세스의 ASP.NET 런타임을 항상 Warmup 모드로 유지하는 preload Enabled 설정
13511정성태1/4/20242161닷넷: 2193. C# - ASP.NET Web Application + OpenAPI(Swashbuckle) 스펙 제공
13510정성태1/3/20242097닷넷: 2192. C# - 특정 실행 파일이 있는지 확인하는 방법 (Linux)
13509정성태1/3/20242121오류 유형: 887. .NET Core 2 이하의 프로젝트에서 System.Runtime.CompilerServices.Unsafe doesn't support netcoreapp2.0.
13508정성태1/3/20242139오류 유형: 886. ORA-28000: the account is locked
13507정성태1/2/20242816닷넷: 2191. C# - IPGlobalProperties를 이용해 netstat처럼 사용 중인 Socket 목록 구하는 방법파일 다운로드1
1  2  3  [4]  5  6  7  8  9  10  11  12  13  14  15  ...