Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you get total amount of RAM the computer has?

Using C#, I want to get the total amount of RAM that my computer has. With the PerformanceCounter I can get the amount of Available ram, by setting:

counter.CategoryName = "Memory"; counter.Countername = "Available MBytes"; 

But I can't seem to find a way to get the total amount of memory. How would I go about doing this?

Update:

MagicKat: I saw that when I was searching, but it doesn't work - "Are you missing an assembly or reference?". I've looked to add that to the References, but I don't see it there.

like image 803
Joel Avatar asked Sep 19 '08 20:09

Joel


People also ask

How much RAM my computer has?

Right-click your taskbar at the bottom of the screen and select “Task Manager” or press Ctrl+Shift+Esc to open it. Select the “Performance” tab and choose “Memory” in the left pane. If you don't see any tabs, click “More Details” first. The total amount of RAM you have installed is displayed here.

What is the total RAM?

To view the total memory on a computer running Windows 7 or Windows Vista, follow the steps below. Press the Windows key , type Properties, and then press Enter . In the System Properties window, the Installed memory (RAM) entry displays the total amount of RAM installed in the computer.


2 Answers

Add a reference to Microsoft.VisualBasic and a using Microsoft.VisualBasic.Devices;.

The ComputerInfo class has all the information that you need.

like image 115
MagicKat Avatar answered Sep 26 '22 10:09

MagicKat


The Windows API function GlobalMemoryStatusEx can be called with p/invoke:

  [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]   private class MEMORYSTATUSEX   {      public uint dwLength;      public uint dwMemoryLoad;      public ulong ullTotalPhys;      public ulong ullAvailPhys;      public ulong ullTotalPageFile;      public ulong ullAvailPageFile;      public ulong ullTotalVirtual;      public ulong ullAvailVirtual;      public ulong ullAvailExtendedVirtual;      public MEMORYSTATUSEX()      {         this.dwLength = (uint)Marshal.SizeOf(typeof(NativeMethods.MEMORYSTATUSEX));      }   }     [return: MarshalAs(UnmanagedType.Bool)]   [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]   static extern bool GlobalMemoryStatusEx([In, Out] MEMORYSTATUSEX lpBuffer); 

Then use like:

ulong installedMemory; MEMORYSTATUSEX memStatus = new MEMORYSTATUSEX(); if( GlobalMemoryStatusEx( memStatus)) {     installedMemory = memStatus.ullTotalPhys; } 

Or you can use WMI (managed but slower) to query TotalPhysicalMemory in the Win32_ComputerSystem class.

like image 28
Philip Rieck Avatar answered Sep 25 '22 10:09

Philip Rieck