Tuesday, May 11, 2010

Using GetVersionEx from C#

using System;
using System.Runtime.InteropServices;

namespace TestGetVersionEx
{
 [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
 public struct OSVERSIONINFOEX
 {
  public static int SizeOf
  {
   get
   {
    return Marshal.SizeOf(typeof(OSVERSIONINFOEX));
   }
  }
      
  public uint dwOSVersionInfoSize;
  public uint dwMajorVersion;
  public uint dwMinorVersion;
  public uint dwBuildNumber;
  public uint dwPlatformId;     
  [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
  public string szCSDVersion;
  public ushort wServicePackMajor;
  public ushort wServicePackMinor;
  public ushort wSuiteMask;
  public byte wProductType;
  public byte wReserved;
 }

 class MainClass
 {
  [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
  [return: MarshalAs(UnmanagedType.Bool)]
  public static extern bool GetVersionEx (ref OSVERSIONINFOEX lpVersionInfo);
  
  public static void Main (string[] args)  
  {
   string OsInfo = string.Empty;
   OSVERSIONINFOEX info = new OSVERSIONINFOEX ();
   info.dwOSVersionInfoSize = (uint)OSVERSIONINFOEX.SizeOf;
   if (OS.GetVersionEx (ref info)) 
   {
    OsInfo = "\n1. Is Windows: " + PlatformDetection.IsWindows + 
    "\n2. dwOSVersionInfoSize: " + info.dwOSVersionInfoSize + 
    "\n3. dwMajorVersion: " + info.dwMajorVersion + 
    "\n4. dwMinorVersion: " + info.dwMinorVersion + 
    "\n5. dwBuildNumber: " + info.dwBuildNumber + 
    "\n6. dwPlatformId: " + info.dwPlatformId + 
    "\n7. wServicePackMajor: " + info.wServicePackMajor + 
    "\n8. wServicePackMinor: " + info.wServicePackMinor + 
    "\n9. wSuiteMask: " + info.wSuiteMask + 
    "\n10. wProductType: " + info.wProductType + 
    "\n11. wReserved: " + info.wReserved + 
    "\nszCSDVersion: " + info.szCSDVersion;
    Console.WriteLine (OsInfo);
   }
  }
 }
}