Get total amount of RAM in C#

To get total RAM in C# we are going to use classes from System.Management namespace and WMI classes.

public static String GetTotalPhysicalMemory()
{
	ManagementScope ms = new ManagementScope();
	ObjectQuery oq = new ObjectQuery("SELECT Capacity FROM Win32_PhysicalMemory");
	ManagementObjectSearcher mos = new ManagementObjectSearcher(ms, oq);
	ManagementObjectCollection moc = mos.Get();
	int amount = 0;
	foreach (ManagementObject moin moc)
	{
		amount += Convert.ToInt32(Convert.ToInt64(mo["Capacity"]) / 1024 / 1024 / 1024);
	}
	ms = null;
	oq = null;
	mos = null;
	moc = null;
	return amount + " GB";
}
Categories: C# Tags: , , , ,
%d bloggers like this: