views:

114

answers:

2

C# static constructor and GetVersion() any suggestions?

Hi, I have defined struct like this in separate file OSVERSIONINFO.cs like this:

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
public struct OSVERSIONINFO
{
    public static int SizeOf 
    {
        get 
        { 
            return Marshal.SizeOf (typeof(OSVERSIONINFO)); 
        }
    }

    public uint dwOSVersionInfoSize;
    public uint dwMajorVersion;
    public uint dwMinorVersion;
    public uint dwBuildNumber;
    public uint dwPlatformId;
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
    public string szCSDVersion;
}

Also I have this file OS.cs in which I have defined the following class:

public static class OS
{
    static OS ()
    {
        OSVERSIONINFO info = new OSVERSIONINFO();
        info.dwOSVersionInfoSize = (uint)OSVERSIONINFO.SizeOf;

        if (!OS.GetVersion(ref info)) 
        {
            Console.WriteLine("Error!!!");
        }

    }

    [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    [return: MarshalAs(UnmanagedType.Bool)]
    public static extern bool GetVersion (ref OSVERSIONINFO lpVersionInfo);
}

Way in static constructor of OS class population of info (instance of OSVERSIONINFO struct) fails? If I call OS.GetVersion in other palce (not OS class) every thing is OK?

+8  A: 

You should use the Environment.OSVersion.Platform property instead.

SLaks
A: 

To answer the question, you need to call GetVersionEx.

SLaks
From MSDN (http://msdn.microsoft.com/en-us/library/ms724439%28VS.85%29.aspx) about GetVersion: This function has been superseded by GetVersionEx. New applications should use GetVersionEx or VerifyVersionInfo. Shame on me, I should read MSDN first. Thank you for your answer and time.
Darius Kucinskas