从WinXP及更高版本获取总内存量

时间:2014-07-28 07:11:34

标签: c# windows memory operating-system

关于这个主题已经有很多答案了,但有没有一种方法可以从XP及以上版本(包括Windows Server 2003)获取Windows系统上的总内存量?

我发现了什么:

Win32_LogicalMemoryConfiguration(已弃用)

Win32_ComputerSystem(支持的最低客户端:Vista)

Microsoft.VisualBasic.Devices.ComputerInfo(根据平台没有XP支持)

THX

1 个答案:

答案 0 :(得分:0)

添加对Microsoft.VisualBasic

的引用
  var info = new Microsoft.VisualBasic.Devices.ComputerInfo();
  Debug.WriteLine(info.TotalPhysicalMemory);
  Debug.WriteLine(info.AvailablePhysicalMemory);
  Debug.WriteLine(info.TotalVirtualMemory);
  Debug.WriteLine(info.AvailableVirtualMemory);

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


您可以使用GlobalMemoryStatusExExample Here

private void DisplayMemory()
{
    // Consumer of the NativeMethods class shown below
    long tm = System.GC.GetTotalMemory(true);
    NativeMethods oMemoryInfo = new NativeMethods();
    this.lblMemoryLoadNumber.Text = oMemoryInfo.MemoryLoad.ToString();
    this.lblIsMemoryTight.Text = oMemoryInfo.isMemoryTight().ToString();
    if (oMemoryInfo.isMemoryTight())
        this.lblIsMemoryTight.Text.Font.Bold = true;
    else
        this.lblIsMemoryTight.Text.Font.Bold = false;

}

本机类包装器。

[CLSCompliant(false)]
public class NativeMethods {

     private     MEMORYSTATUSEX msex;
     private uint _MemoryLoad;
     const int MEMORY_TIGHT_CONST = 80;

     public bool isMemoryTight()
      {
         if (_MemoryLoad > MEMORY_TIGHT_CONST )
            return true;
          else
             return false;
     }

          public uint MemoryLoad
     {
        get { return _MemoryLoad; }
         internal set { _MemoryLoad = value; }
      }

       public NativeMethods() {

        msex = new MEMORYSTATUSEX();
        if (GlobalMemoryStatusEx(msex)) {

                  _MemoryLoad = msex.dwMemoryLoad;
             //etc.. Repeat for other structure members        

        }
            else
             // Use a more appropriate Exception Type. 'Exception' should almost never be thrown
             throw new Exception("Unable to initalize the GlobalMemoryStatusEx API");
    }

    [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()
        {
                  this.dwLength = (uint) Marshal.SizeOf(typeof( MEMORYSTATUSEX ));
        }
    }


     [return: MarshalAs(UnmanagedType.Bool)]
     [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
     static extern bool GlobalMemoryStatusEx( [In, Out] MEMORYSTATUSEX lpBuffer);

}