get system total memory in csharp

You can use the PerformanceCounter class from the System.Diagnostics namespace to get the amount of free memory on the system. Here is an example:

main.cs
using System.Diagnostics;

// ...

// Create a PerformanceCounter object for the Available Bytes counter
var pc = new PerformanceCounter("Memory", "Available Bytes");

// Get the current available memory in bytes
long availableMemory = pc.RawValue;

Console.WriteLine($"Available memory: {availableMemory} bytes");
315 chars
12 lines

To get the total amount of physical memory on the system, you can use the ManagementObjectSearcher class from the System.Management namespace:

main.cs
using System.Management;

// ...

// Select the "TotalPhysicalMemory" property from the "Win32_ComputerSystem" class
var searcher = new ManagementObjectSearcher("SELECT TotalPhysicalMemory FROM Win32_ComputerSystem");
var result = searcher.Get().Cast<ManagementObject>().FirstOrDefault();

// Get the total physical memory in bytes
long totalMemory = result == null ? 0 : (long)result["TotalPhysicalMemory"];

Console.WriteLine($"Total memory: {totalMemory} bytes");
467 chars
13 lines

Note that the TotalPhysicalMemory property is only available on some versions of Windows. If it is not available, result will be null and totalMemory will be 0.

gistlibby LogSnag