Para obtener el total de memoria RAM utilizada en nuestro equipo mediante C# .Net, les comparto la siguiente clase que organice, la cual obtiene la memoria disponible y la memoria total del equipo en el que se ejecuta el código (En megabytes).
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 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 | public static class MonitorRam { [DllImport( "psapi.dll" , SetLastError = true )] [ return : MarshalAs(UnmanagedType.Bool)] public static extern bool GetPerformanceInfo([Out] out InformacionRendimiento PerformanceInformation, [In] int Size); /// Estructura que nos sera regresada por el metodo GetPerformanceInfo [StructLayout(LayoutKind.Sequential)] public struct InformacionRendimiento { public int Size; public IntPtr CommitTotal; public IntPtr CommitLimit; public IntPtr CommitPeak; public IntPtr PhysicalTotal; public IntPtr PhysicalAvailable; public IntPtr SystemCache; public IntPtr KernelTotal; public IntPtr KernelPaged; public IntPtr KernelNonPaged; public IntPtr PageSize; public int HandlesCount; public int ProcessCount; public int ThreadCount; } #region HELPERS public static Int64 GetRamDisponible() { InformacionRendimiento pi = new InformacionRendimiento(); if (GetPerformanceInfo( out pi, Marshal.SizeOf(pi))) { return Convert.ToInt64((pi.PhysicalAvailable.ToInt64() * pi.PageSize.ToInt64() / 1048576)); } else { return -1; } } public static Int64 GetRamTotal() { InformacionRendimiento pi = new InformacionRendimiento(); if (GetPerformanceInfo( out pi, Marshal.SizeOf(pi))) { return Convert.ToInt64((pi.PhysicalTotal.ToInt64() * pi.PageSize.ToInt64() / 1048576)); } else { return -1; } } #endregion } |
Y para obtener la memoria RAM utilizada solo hacemos una resta:
1 2 3 4 5 6 7 | Int64 disponible = MonitorRam.GetRamDisponible(); Int64 total = MonitorRam.GetRamTotal(); //obtenemos la memoria utilizada mediante una resta Int64 utilizada = total - disponible; Console.WriteLine( "Memoria disponible: " + disponible.ToString()); Console.WriteLine( "Memoria utilizada: " + utilizada.ToString()); Console.WriteLine( "Total memoria RAM: " + total.ToString()); |