In this brief article, we'll explain you how to retrieve the available amount of RAM in your system with C# in WinForms.
1. Import System.Management
In some examples, you'll need to add the following reference in your project to retrieve information about the system:
using System.Management;
However, in some Visual Studio versions (specifically in 2010 and later) you'll need to add the reference (.DLL
) in your project manually too. To do that follow these steps:
-
Right Click on Project, Add References
-
Select the Assemblies (framework) Tab and Search for
System.Management
and finally add the reference and click OK.
We need to add the System.Management
to create queries in WMI Classes
. Read more about retrieving WMI Classes in .NET in msdn here.
2. Retrieve RAM amount
In order to retrieve the available amount of RAM in the operative system with C# is through the Win32_OperatingSystem WMI class, that represents a Windows-based operating system installed on a computer. From a created instance you will be able to extract some properties that are related to the RAM:
ObjectQuery wql = new ObjectQuery("SELECT * FROM Win32_OperatingSystem");
ManagementObjectSearcher searcher = new ManagementObjectSearcher(wql);
ManagementObjectCollection results = searcher.Get();
foreach (ManagementObject result in results)
{
Console.WriteLine("Total Visible Memory: {0} KB", result["TotalVisibleMemorySize"]);
Console.WriteLine("Free Physical Memory: {0} KB", result["FreePhysicalMemory"]);
Console.WriteLine("Total Virtual Memory: {0} KB", result["TotalVirtualMemorySize"]);
Console.WriteLine("Free Virtual Memory: {0} KB", result["FreeVirtualMemory"]);
}
/* Outputs:
Total Visible Memory: 25054184 KB
Free Physical Memory: 17048656 KB
Total Virtual Memory: 29117416 KB
Free Virtual Memory: 18637080 KB
*/
The output of the code displays the value of 4 properties of the ManagementObject that are:
TotalVisibleMemorySize
: This value specifies the total amount, in kilobytes, of physical memory available to the operating system. This value does not necessarily indicate the true amount of physical memory, but what is reported to the operating system as available to it.FreePhysicalMemory
: Number, in kilobytes, of physical memory currently unused and available.TotalVirtualMemorySize
: Number, in kilobytes, of virtual memory. For example, this may be calculated by adding the amount of total RAM to the amount of paging space, that is, adding the amount of memory in or aggregated by the computer system to the property, SizeStoredInPagingFiles.FreeVirtualMemory
: Specifies the number, in kilobytes, of virtual memory currently unused and available.
Happy coding !