RAM usage in NET 8

Dani_S 4,501 Reputation points
2024-02-25T14:40:50.5966667+00:00

Hi, I want in C# .Net 8 to calculate the usage of RAM. Is it the way ? User's image

   System.Diagnostics.PerformanceCounter _ramCounter = new System.Diagnostics.PerformanceCounter("Memory", "Available MBytes");
RamCapacity = GetTotalMemoryInGb();
**RamUsage = RamCapacity - (_ramCounter.NextValue() / (1024D));**
 private static ulong **GetTotalMemoryInGb**()
 {
     var query = "SELECT Capacity FROM Win32_PhysicalMemory";
     var searcher = new ManagementObjectSearcher(query);
     ulong capacityGB = 0;
     foreach (var WniPART in searcher.Get())
     {
         var capacity = Convert.ToUInt64(WniPART.Properties["Capacity"].Value);
         var capacityKB = capacity / 1024;
         var capacityMB = capacityKB / 1024;
         capacityGB = capacityMB / 1024;
 }
 return capacityGB;
}
Developer technologies .NET Other
0 comments No comments
{count} votes

Accepted answer
  1. Anonymous
    2024-02-26T03:18:44.1966667+00:00

    Hi @דני שטרית , Welcome to Microsoft Q&A,

    You can use the GlobalMemoryStatusEx method in the System.Runtime.InteropServices.Marshal class. This method provides information about the system's memory status, including total memory and available memory. In this example, the MemoryInfo class defines a structure MEMORYSTATUSEX that contains system memory status information. Then use the DllImport attribute to declare the GlobalMemoryStatusEx function, which can obtain memory status information from the system kernel 32. The MemoryInfo.GetMemoryStatus method extracts this information and returns total memory and available memory.

    Here is sample code using this approach:

    using System;
    using System.Runtime.InteropServices;
    
    namespace xxx
    {
        public class MemoryInfo
        {
            [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
            private class MEMORYSTATUSEX
            {
                public uint dwLength;
                public uint dwMemoryLoad;
                public ulong ullTotalPhys;
                public ulong ullAvailPhys;
                public ulong ullTotalPageFile;
                public ulong ullAvailPageFile;
                public ulong ullTotalVirtual;
                public ulong ullAvailVirtual;
                public ulong ullAvailExtendedVirtual;
    
                public MEMORYSTATUSEX()
                {
                    dwLength = (uint)Marshal.SizeOf(typeof(MEMORYSTATUSEX));
                }
            }
    
            [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
            [return: MarshalAs(UnmanagedType.Bool)]
            private static extern bool GlobalMemoryStatusEx([In, Out] MEMORYSTATUSEX lpBuffer);
    
            public static void GetMemoryStatus(out double totalMemoryGB, out double availableMemoryGB)
            {
                var memoryStatus = new MEMORYSTATUSEX();
                if (GlobalMemoryStatusEx(memoryStatus))
                {
                    totalMemoryGB = ConvertBytesToGB(memoryStatus.ullTotalPhys);
                    availableMemoryGB = ConvertBytesToGB(memoryStatus.ullAvailPhys);
                }
                else
                {
                    throw new InvalidOperationException("Failed to retrieve memory status.");
                }
            }
            private static double ConvertBytesToGB(ulong bytes)
            {
                return bytes / (1024.0 * 1024.0 * 1024.0);
            }
        }
        internal class Program
        {
            static void Main(string[] args)
            {
                double totalMemoryGB, availableMemoryGB;
                MemoryInfo.GetMemoryStatus(out totalMemoryGB, out availableMemoryGB);
                Console.WriteLine("Total Memory: {0:F2} GB", totalMemoryGB);
                Console.WriteLine("Available Memory: {0:F2} GB", availableMemoryGB);
                Console.ReadLine();
            }
        }
    }
    

    Best Regards,

    Jiale


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment". 

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.