In this tutorial, I will show you how to add a reference to the console project and how can be used.
First, create a new folder named FreeRam and start a new console project with these commands:
1 | dotnet new console |
In this project, I will use the System.Management.
I used this command to add this reference to the project:
1 | dotnet add package System.Management |
The System. Management let you create an object and this is used to take the information you need.
The source code is simple to understand, you can see it below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | using System; using System.Management; namespace ConsoleApp1 { public class FreeRAM { static void Main(string[] args) { //... get the total physical memory size ManagementClass class_man_phy = new ManagementClass("Win32_PhysicalMemory"); ManagementObjectCollection man_obj_collection_phy = class_man_phy.GetInstances(); double available=0, capacity=0; foreach (ManagementObject m_phy in man_obj_collection_phy) { capacity += ((Math.Round(Int64.Parse(m_phy.Properties["Capacity"].Value.ToString()) / 1024 / 1024 / 1024.0, 1))); } man_obj_collection_phy.Dispose(); class_man_phy.Dispose(); //... get the size of memory available ManagementClass class_man_free = new ManagementClass("Win32_PerfFormattedData_PerfOS_Memory"); ManagementObjectCollection man_obj_collection_free = class_man_free.GetInstances(); foreach (ManagementObject m_free in man_obj_collection_free) { available += ((Math.Round(Int64.Parse(m_free.Properties["AvailableMBytes"].Value.ToString()) / 1024.0, 1))); } man_obj_collection_free.Dispose(); class_man_free.Dispose(); Console.WriteLine("Total memory : " + capacity.ToString() + "G"); Console.WriteLine("may by use :" + available.ToString() + "G"); Console.WriteLine("already used : " + ((capacity - available)).ToString() + "G," + (Math.Round((capacity - available) / capacity * 100, 0)).ToString() + "%"); Console.ReadKey(); } } } |
Finally, use the run command to get all information about the memory system:
1 2 3 4 | dotnet run Total memory: 8G may by use:3.2G already used : 4.8G,60% |