How to: Get Total Physical Memory
Q: My app needs to know how much RAM the machine it's running on has. How can this information be aquired ?
Is there any _managed_ way of getting total physical memory installed in the machine ?
You can retrieve the amount of physical memory on the computer by using WMI (You could use a WMI query, the property is "TotalPhysicalMemory" which is in the "Win32_ComputerSystem" class.). However: WMI would almost always be the slowest way to retrieve system values using C#.
Therefore I advice to use Win32 API - GlobalMemoryStatus function included in kernel32.dll:
public struct MemoryStatus { public uint Length; public uint MemoryLoad; public uint TotalPhysical; public uint AvailablePhysical; public uint TotalPageFile; public uint AvailablePageFile; public uint TotalVirtual; public uint AvailableVirtual; } [DllImport("kernel32.dll")] public static extern void GlobalMemoryStatus(out MemoryStatus stat);
From managed code we can use it like so:
MemoryStatus stat = new MemoryStatus(); GlobalMemoryStatus(out stat); long ram = (long)stat.TotalPhysical;
Hope this helps.
Saturday, June 14, 2008 5:59 AM