Tuesday, September 10, 2013

OSVersion

MarkdownPad Document

Just recently I was involved in a discussion about logging and the need to include the name of the operation system and the service pack level in the application log file.

While you can get to this information in a number of ways, it is important that it will work as expected even for future versions of Windows.

The following code shows a console application that displays the name of the operating system along with the current service pack level.

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Operating System : {0} ({1} bit) ", GetOperationSystemName(), IntPtr.Size == 4 ? "32" : "64");
        Console.WriteLine("Service Pack : {0}", Environment.OSVersion.ServicePack);
    }

    private static string GetOperationSystemName()
    {
        var searcher = new ManagementObjectSearcher("SELECT Caption FROM Win32_OperatingSystem");
        var managementObject = searcher.Get().OfType<ManagementObject>().FirstOrDefault();
        return managementObject != null ? managementObject["Caption"].ToString() : "Unknown OS";
    }
}

Running the console application displays the following:

.\OSVersion.exe

Operating System : Microsoft Windows 7 Enterprise  (64 bit)
Service Pack : Service Pack 1

2 comments:

Runar Ovesen Hjerpbakk said...

I wonder if this is supported in Xamarin Touch :)

Bernhard Richter said...

I'm afraid this is only an option if you're on the Windows platform :)

On the Mac (Mono), you can get some information from the OSVersion class.

Console.WriteLine(Environment.OSVersion)

This reports: Unix 12.4.0.0 on my iMac :)