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)
13501정성태12/25/20232087개발 환경 구성: 700. WSL + uwsgi - IPv6로 바인딩하는 방법
13500정성태12/24/20232178디버깅 기술: 194. Windbg - x64 가상 주소를 물리 주소로 변환
13498정성태12/23/20232824닷넷: 2186. 한국투자증권 KIS Developers OpenAPI의 C# 래퍼 버전 - eFriendOpenAPI NuGet 패키지
13497정성태12/22/20232294오류 유형: 885. Visual Studiio - error : Could not connect to the remote system. Please verify your connection settings, and that your machine is on the network and reachable.
13496정성태12/21/20232310Linux: 66. 리눅스 - 실행 중인 프로세스 내부의 환경변수 설정을 구하는 방법 (gdb)
13495정성태12/20/20232319Linux: 65. clang++로 공유 라이브러리의 -static 옵션 빌드가 가능할까요?
13494정성태12/20/20232501Linux: 64. Linux 응용 프로그램의 (C++) so 의존성 줄이기(ReleaseMinDependency) - 두 번째 이야기
13493정성태12/19/20232559닷넷: 2185. C# - object를 QueryString으로 직렬화하는 방법
13492정성태12/19/20232263개발 환경 구성: 699. WSL에 nopCommerce 예제 구성
13491정성태12/19/20232232Linux: 63. 리눅스 - 다중 그룹 또는 사용자를 리소스에 권한 부여
13490정성태12/19/20232345개발 환경 구성: 698. Golang - GLIBC 의존을 없애는 정적 빌드 방법
13489정성태12/19/20232133개발 환경 구성: 697. GoLand에서 ldflags 지정 방법
13488정성태12/18/20232067오류 유형: 884. HTTP 500.0 - 명령행에서 실행한 ASP.NET Core 응용 프로그램을 실행하는 방법
13487정성태12/16/20232381개발 환경 구성: 696. C# - 리눅스용 AOT 빌드를 docker에서 수행 [1]
13486정성태12/15/20232195개발 환경 구성: 695. Nuget config 파일에 값 설정/삭제 방법
13485정성태12/15/20232088오류 유형: 883. dotnet build/restore - error : Root element is missing
13484정성태12/14/20232162개발 환경 구성: 694. Windows 디렉터리 경로를 WSL의 /mnt 포맷으로 구하는 방법
13483정성태12/14/20232298닷넷: 2184. C# - 하나의 resource 파일을 여러 프로그램에서 (AOT 시에도) 사용하는 방법파일 다운로드1
13482정성태12/13/20232821닷넷: 2183. C# - eFriend Expert OCX 예제를 .NET Core/5+ Console App에서 사용하는 방법 [2]파일 다운로드1
13481정성태12/13/20232267개발 환경 구성: 693. msbuild - .NET Core/5+ 프로젝트에서 resgen을 이용한 리소스 파일 생성 방법파일 다운로드1
13480정성태12/12/20232609개발 환경 구성: 692. Windows WSL 2 + Chrome 웹 브라우저 설치
13479정성태12/11/20232302개발 환경 구성: 691. WSL 2 (Ubuntu) + nginx 환경 설정
13477정성태12/8/20232483닷넷: 2182. C# - .NET 7부터 추가된 Int128, UInt128 [1]파일 다운로드1
13476정성태12/8/20232207닷넷: 2181. C# - .NET 8 JsonStringEnumConverter의 AOT를 위한 개선파일 다운로드1
13475정성태12/7/20232279닷넷: 2180. .NET 8 - 함수 포인터에 대한 Reflection 정보 조회파일 다운로드1
13474정성태12/6/20232133개발 환경 구성: 690. 닷넷 코어/5+ 버전의 ilasm/ildasm 실행 파일 구하는 방법 - 두 번째 이야기
1  2  3  4  [5]  6  7  8  9  10  11  12  13  14  15  ...