What does Environment.OSVersion return on Windows 10?
Unfortunately, the answer is, it depends.
Consider the following code:
Console.WriteLine(Environment.OSVersion.ToString());
Depending how you execute the code, you may get differing results:
Visual Studio Version | Project Type | Output |
---|---|---|
2015 Update 1 | Console App |
Microsoft Windows NT 6.2.9200.0
|
2015 Update 1 | Unit Test |
Microsoft Windows NT 10.0.10586.0
|
2015 (No update 1) | Console App |
Microsoft Windows NT 6.2.9200.0
|
2015 (No update 1) | Unit Test |
Microsoft Windows NT 6.2.9200.0
|
So, how can we get our console application to be consistent with the test application in VS 2015 update 1? The key is manifest files. According to the Operating System Version documentation:
For applications that have been manifested for Windows 8.1 or Windows 10. Applications not manifested for Windows 8.1 or Windows 10 will return the Windows 8 OS version value (6.2). To manifest your applications for Windows 8.1 or Windows 10, refer to Targeting your application for Windows.
So we can add a manifest file to our console application to specify Windows 10 compatibility:
<?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"/>
<compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1">
<application>
<!-- Windows 10 -->
<supportedOS Id="{8e0f7a12-bfb3-4fe8-b9a5-48fd50a15a9a}" />
</application>
</compatibility>
</assembly>
Now, when we run the console application, we get the output of Microsoft Windows NT 10.0.10586.0
So, what changed in Visual Studio 2015 Update 1? This is speculation, but I am guessing they added a manifest to the executable the runs the unit tests behind the scenes, which caused the Environment.OSVersion to return the new value for Windows 10. As the documentation states:
Identifying the current operating system is usually not the best way to determine whether a particular operating system feature is present. This is because the operating system may have had new features added in a redistributable DLL. Rather than using the Version API Helper functions to determine the operating system platform or version number, test for the presence of the feature itself.
So, if you plan on using Enivronment.OSVersion
in the future, be sure to understand the different values it could return depending on how the code is hosted.