Wednesday, July 11, 2007

Determining the amount of memory available on a system in C#

From what I could tell, I could not find any native .NET class that could return the total amount of memory thats available on a system. But one can use PInvoke to get at this information. Here is the sample
public struct MEMORYSTATUS
{
    public  uint dwLength;
    public  uint dwMemoryLoad;
    public  uint dwTotalPhys;
    public  uint dwAvailPhys;
    public  uint dwTotalPageFile;
    public  uint dwAvailPageFile;
    public  uint dwTotalVirtual;
    public  uint dwAvailVirtual;
}
public struct SYSTEM_INFO
{
    public  uint  dwOemId;
    public  uint  dwPageSize;
    public  uint  lpMinimumApplicationAddress;
    public    uint  lpMaximumApplicationAddress;
    public  uint  dwActiveProcessorMask;
    public  uint  dwNumberOfProcessors;
    public  uint  dwProcessorType;
    public  uint  dwAllocationGranularity;
    public  uint  dwProcessorLevel;
    public  uint  dwProcessorRevision;       
}
[DllImport("kernel32.dll")]
extern static void GlobalMemoryStatus(ref MEMORYSTATUS lpBuffer);

[DllImport("kernel32.dll")]
extern static void GetSystemInfo(ref SYSTEM_INFO lpSystemInfo);

No comments: