0

I need to get information about how much total RAM and how much virtual memory. And also how much virtual memory and RAM is currently used by the system, as in Task Manager. At the moment, I just figured out how to get the total amount of RAM, I have difficulties with the rest

        ObjectQuery wql = new ObjectQuery("SELECT * FROM Win32_OperatingSystem");
        ManagementObjectSearcher searcher = new ManagementObjectSearcher(wql);
        ManagementObjectCollection results = searcher.Get();

        double totalMemory = 0;

        foreach (ManagementObject item in results)
        {
            var res = Convert.ToDouble(item["TotalVisibleMemorySize"]);
            totalMemory = Math.Round((res / 1024), 2);
        }
JonnyJon44
  • 73
  • 1
  • 11
  • 1
    [How do you get total amount of RAM the computer has?](https://stackoverflow.com/questions/105031/how-do-you-get-total-amount-of-ram-the-computer-has) answers both questions. 1. Total RAM installed: `memStatus.ullTotalPhys`, 2. Total RAM available: `memStatus.ullAvailPhys` – MindSwipe Apr 13 '22 at 09:17
  • [How to convert the total supported memory using the Win32_ComputerSystem class](https://stackoverflow.com/a/54498549/7444103) -- Uses `GetPhysicallyInstalledSystemMemory()`, `GlobalMemoryStatusEx()` and WMI's `Win32_PhysicalMemory` class (+ comparisons). – Jimi Apr 13 '22 at 11:24

1 Answers1

0

Firstly you can add references to your project. In the opening form select Assemblies and after that select Framework. You can see a list of Assemblies. Select "System. Management" from the list and add it to the project. Then use this code:

public string ConvertKB(string str)
    {
        int val = Int32.Parse(str);
        val = (int)((val / 1024) / 1024);
        return val.ToString() + " GB";
    }

    public void GetRAMUse()
    {
        ObjectQuery wql = new ObjectQuery("SELECT * FROM Win32_OperatingSystem");
        ManagementObjectSearcher searcher = new ManagementObjectSearcher(wql);
        ManagementObjectCollection results = searcher.Get();

        foreach (ManagementObject result in results)
        {
            listBox1.Items.Add("Total Visible Memory: "  + ConvertKB(result["TotalVisibleMemorySize"].ToString()));
            listBox1.Items.Add("Free Physical Memory: "  + ConvertKB(result["FreePhysicalMemory"].ToString()));
            listBox1.Items.Add("Total Virtual Memory: "  + ConvertKB(result["TotalVirtualMemorySize"].ToString()));
            listBox1.Items.Add("Free Virtual Memory:  "  + ConvertKB(result["FreeVirtualMemory"].ToString()));
        }

    }
Ramin Faracov
  • 3,032
  • 1
  • 2
  • 8