Get System Memory Size in .NET

By Robbe Morris

Quick tip showing how to use .NET to get the current system's memory size.

using System.Management;

public static string GetSystemMemory()
{
    double bytes = 0;

    var mos = new ManagementObjectSearcher();
      mos.Query = new ObjectQuery("SELECT TotalPhysicalMemory FROM Win32_ComputerSystem");

    foreach (ManagementObject mo in mos.Get())
    {
// See related sampel below for ToDouble code.
      bytes += ToDouble(mo["TotalPhysicalMemory"].ToString(),6);
    }

// See related sample below for user friendly byte conversion.
    return GetBytes(bytes,false);

}

Related FAQs

Some very old code I found upgraded a tad to be current. Used to safely convert a string to a double rounded off to the nearest decimal.
Convert bytes or kilobytes to kilobytes, megabytes, or gigabytes in .NET
Get System Memory Size in .NET  (2524 Views)