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]

... 16  17  18  19  20  21  22  23  [24]  25  26  27  28  29  30  ...
NoWriterDateCnt.TitleFile(s)
13026정성태4/11/20228533.NET Framework: 1191. C 언어로 작성된 FFmpeg Examples의 C# 포팅 전체 소스 코드 [3]
13025정성태4/11/20227894.NET Framework: 1190. C# - ffmpeg(FFmpeg.AutoGen)를 이용한 vaapi_encode.c, vaapi_transcode.c 예제 포팅
13024정성태4/7/20226403.NET Framework: 1189. C# - 런타임 환경에 따라 달라진 AppDomain.GetCurrentThreadId 메서드
13023정성태4/6/20226690.NET Framework: 1188. C# - ffmpeg(FFmpeg.AutoGen)를 이용한 transcoding.c 예제 포팅 [3]
13022정성태3/31/20226588Windows: 202. 윈도우 11 업그레이드 - "PC Health Check"를 통과했지만 여전히 업그레이드가 안 되는 경우 해결책
13021정성태3/31/20226767Windows: 201. Windows - INF 파일을 이용한 장치 제거 방법
13020정성태3/30/20226484.NET Framework: 1187. RDP 접속 시 WPF UserControl의 Unloaded 이벤트 발생파일 다운로드1
13019정성태3/30/20226484.NET Framework: 1186. Win32 Message를 Code로부터 메시지 이름 자체를 구하고 싶다면?파일 다운로드1
13018정성태3/29/20227013.NET Framework: 1185. C# - Unsafe.AsPointer가 반환한 포인터는 pinning 상태일까요? [5]
13017정성태3/28/20226858.NET Framework: 1184. C# - GC Heap에 위치한 참조 개체의 주소를 알아내는 방법 - 두 번째 이야기 [3]
13016정성태3/27/20227678.NET Framework: 1183. C# 11에 추가된 ref 필드의 (우회) 구현 방법파일 다운로드1
13015정성태3/26/20229052.NET Framework: 1182. C# 11 - ref struct에 ref 필드를 허용 [1]
13014정성태3/23/20227624VC++: 155. CComPtr/CComQIPtr과 Conformance mode 옵션의 충돌 [1]
13013정성태3/22/20225975개발 환경 구성: 641. WSL 우분투 인스턴스에 파이썬 2.7 개발 환경 구성하는 방법
13012정성태3/21/20225293오류 유형: 803. C# - Local '...' or its members cannot have their address taken and be used inside an anonymous method or lambda expression
13011정성태3/21/20226766오류 유형: 802. 윈도우 운영체제에서 웹캠 카메라 인식이 안 되는 경우
13010정성태3/21/20225708오류 유형: 801. Oracle.ManagedDataAccess.Core - GetTypes 호출 시 "Could not load file or assembly 'System.DirectoryServices.Protocols...'" 오류
13009정성태3/20/20227290개발 환경 구성: 640. docker - ibmcom/db2 컨테이너 실행
13008정성태3/19/20226592VS.NET IDE: 176. 비주얼 스튜디오 - 솔루션 탐색기에서 프로젝트를 선택할 때 csproj 파일이 열리지 않도록 만드는 방법
13007정성태3/18/20226211.NET Framework: 1181. C# - Oracle.ManagedDataAccess의 Pool 및 그것의 연결 개체 수를 알아내는 방법파일 다운로드1
13006정성태3/17/20227271.NET Framework: 1180. C# - ffmpeg(FFmpeg.AutoGen)를 이용한 remuxing.c 예제 포팅
13005정성태3/17/20226105오류 유형: 800. C# - System.InvalidOperationException: Late bound operations cannot be performed on fields with types for which Type.ContainsGenericParameters is true.
13004정성태3/16/20226133디버깅 기술: 182. windbg - 닷넷 메모리 덤프에서 AppDomain에 걸친 정적(static) 필드 값을 조사하는 방법
13003정성태3/15/20226305.NET Framework: 1179. C# - (.NET Framework를 위한) Oracle.ManagedDataAccess 패키지의 성능 카운터 설정 방법
13002정성태3/14/20227071.NET Framework: 1178. C# - ffmpeg(FFmpeg.AutoGen)를 이용한 http_multiclient.c 예제 포팅
13001정성태3/13/20227435.NET Framework: 1177. C# - 닷넷에서 허용하는 메서드의 매개변수와 호출 인자의 최대 수
... 16  17  18  19  20  21  22  23  [24]  25  26  27  28  29  30  ...