Retrieving the System's Total Physical Memory

Recently I was creating an app in which I needed to display the total physical memory inside a label. At first I was tempted to retrieve the memory using the Capacity property from Win32_PhysicalMemory, but it seems that this property retrieves the memory from each module. Although it does the job, I found out that is more efficient to retrieve the total physical memory using the TotalPhysicalMemory property from the Win32_ComputerSystem WMI class.

The following code shows you how to retrieve it using a foreach loop. Note that this property retrieves the memory in bytes and I've did some calculations to display it in GB. Then, this method can be used to display the memory amount inside a label... or whatever.

private static String getRAMsize()
        {
            ManagementClass mc = new ManagementClass("Win32_ComputerSystem");
            ManagementObjectCollection moc = mc.GetInstances();
            foreach (ManagementObject item in moc)
            {
                return Convert.ToString(Math.Round(Convert.ToDouble(item.Properties["TotalPhysicalMemory"].Value) / 1073741824, 2)) + " GB";
            }

            return "RAMsize";
        }

1 comment: