Saturday, July 3, 2010

Determine RAM Usage

To read-out the RAM usage of the computer using C#, we use the class PerformanceCounter again, which has been introduced in the previous post on how to determine the CPU usage.
To determine the RAM usage though, we use "Memory" as CategoryName and "Available MBytes" as CounterName.
Furthermore, here NextValue() needs no reference point, so a singular call suffices.
A PerformanceCounter with this settings does not read the exact RAM usage though, but the size of the RAM which is not used (in MB).
In the taskmanager we find this value under "System Performance" - "Physical Memory - Available".
Now to the code:
using System.Diagnostics;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

        }

        PerformanceCounter RAMCounter = new PerformanceCounter(); // instance of the class PerformanceCounter

        private void Form1_Load(object sender, EventArgs e)
        {
            // initialize with the mentioned values
            RAMCounter.CategoryName = "Memory";
            RAMCounter.CounterName = "Available MBytes";
        }

        // read the RAM usage when clicking
        private void button1_Click(object sender, EventArgs e)
        {
            GetRAMUsage();
        }

        private void GetRAMUsage()
        {
            // call NextValue() and output the result
            MessageBox.Show((RAMCounter.NextValue()).ToString());
        }
    }
}

No comments:

Post a Comment