How To Determine the Operating System Service Pack Level in Visual C# .NET (304721)



The information in this article applies to:

  • Microsoft Visual C# .NET (2002)

This article was previously published under Q304721
For a Microsoft Visual Basic .NET version of this article, see 304722.
For a Microsoft Visual C++ .NET version of this article, see 307393.

This article refers to the following Microsoft .NET Framework Class Library namespace:
  • System.Runtime.InteropServices

SUMMARY

This step-by-step article shows you how to build the GetServicePack method.

MORE INFORMATION

The OSVersion property, which is provided for obtaining operating system (OS) information, does not contain a member that provides service pack information. To determine what service pack is installed, you must call the GetVersionEx API function directly. Typically, it is better to avoid this practice; the .NET Framework provides access to the underlying API sets in a much more consistent (and easier to use) manner than by calling the individual API functions.

When you must call an API function directly, you can do this through the Interop layer of the .NET Framework. The sample code in this article gives a method, GetServicePack, that returns the service pack level.

NOTE: The OSVERSIONINFO structure contains a fixed-length string, szCSDVersion. Because fixed-length strings are no longer supported, you must provide the marshalling information for this member. Do this by using the attribute (denoted by []) preceding the member name.
  1. Open a new C# .NET console application.
  2. Open the code window for class1.cs, and then delete all of the code.
  3. Paste the following sample code in class1.cs:
    using System;
    using System.Reflection;
    using System.Runtime.InteropServices;
    
    class Class1
    {
        static void Main(string[] args)
        {
    	Console.WriteLine(GetServicePack());
        }
        [StructLayout(LayoutKind.Sequential)]
        public struct OSVERSIONINFO 
        {
    	public int dwOSVersionInfoSize;
    	public int dwMajorVersion;
    	public int dwMinorVersion;
    	public int dwBuildNumber;
    	public int dwPlatformId;
    	[MarshalAs(UnmanagedType.ByValTStr, SizeConst=128)]
    	public string szCSDVersion;
        }
        [DllImport("kernel32.Dll")] public static extern short GetVersionEx(ref OSVERSIONINFO o);
        static public  string GetServicePack()
        {
    	OSVERSIONINFO os = new OSVERSIONINFO();
    	os.dwOSVersionInfoSize=Marshal.SizeOf(typeof(OSVERSIONINFO)); 
    	GetVersionEx(ref os);
    	if (os.szCSDVersion=="")					 
        	    return "No Service Pack Installed";
    	else
       	    return os.szCSDVersion;
        }
    }
    					
  4. Press CTRL+F5 to build and then run the project. The service pack information appears in the console window.

Modification Type:MinorLast Reviewed:10/6/2004
Keywords:kbhowto kbSample KB304721