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.