How can I get the total physical memory in C#?

前端 未结 5 875
执笔经年
执笔经年 2020-12-15 23:56

I am using the GlobalMemoryStatusEx function to retrieve information about memory, but this function doesn\'t work correctly. It returns 0 for all properties. I

相关标签:
5条回答
  • 2020-12-16 00:29

    you can use this templates:

    long memory = Process.GetCurrentProcess().PeakVirtualMemorySize64;
    

    And another properties with names Peak*64

    0 讨论(0)
  • 2020-12-16 00:38

    How about:

    My.Computer.Info.TotalPhysicalMemory
    My.Computer.Info.AvailablePhysicalMemory
    
    0 讨论(0)
  • 2020-12-16 00:39

    You forgot to set statEX.dwLength before calling GlobalMemoryStatusEx.

    MEMORYSTATUSEX statEX = new MEMORYSTATUSEX();
    statEX.dwLength = (uint)Marshal.SizeOf(typeof(MEMORYSTATUSEX));
    GlobalMemoryStatusEx(ref statEX);
    
    0 讨论(0)
  • 2020-12-16 00:46

    I find my mistake from: http://www.pinvoke.net/default.aspx/kernel32/GlobalMemoryStatusEx.html

    I Changed

    internal static extern bool GlobalMemoryStatusEx(ref MEMORYSTATUSEX lpBuffer);
    

    To

    static extern bool GlobalMemoryStatusEx([In, Out] MEMORYSTATUSEX lpBuffer);
    

    and changed

    GlobalMemoryStatusEx(ref statEX);
    

    To

    GlobalMemoryStatusEx(statEX);
    

    It work correctly. Tanks

    0 讨论(0)
  • 2020-12-16 00:49

    If c# you can:

    Reference the Microsoft.VisualBasic assembly. Then import Microsoft.VisualBasic.Devices namespace.
    And finally use ComputerInfo to get the total physical memory.

    int bytesPerMebibyte = (1 << 20);  // http://physics.nist.gov/cuu/Units/binary.html
    ComputerInfo myCompInfo = new ComputerInfo();
    string physicalMemory = "Physical Memory: "
        + (myCompInfo.TotalPhysicalMemory / bytesPerMebibyte) + " MB";
    
    0 讨论(0)
提交回复
热议问题