Microsoft KB Archive/304721

= How To Determine the Operating System Service Pack Level in Visual C# .NET =

Article ID: 304721

Article Last Modified on 10/6/2004

-

APPLIES TO


 * Microsoft Visual C# .NET 2002 Standard Edition

-



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.  Open a new C# .NET console application. Open the code window for class1.cs, and then delete all of the code.  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(&quot;kernel32.Dll&quot;)] 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==&quot;&quot;) return &quot;No Service Pack Installed&quot;; else return os.szCSDVersion; } }                    Press CTRL+F5 to build and then run the project. The service pack information appears in the console window.

Keywords: kbhowto kbsample KB304721

-

[mailto:TECHNET@MICROSOFT.COM Send feedback to Microsoft]

© Microsoft Corporation. All rights reserved.