代码之家  ›  专栏  ›  技术社区  ›  Joel

如何获得计算机的RAM总量?

  •  67
  • Joel  · 技术社区  · 16 年前

    使用C#,我想得到我的计算机的RAM总量。

    counter.CategoryName = "Memory";
    counter.Countername = "Available MBytes";
    

    但是我似乎找不到一种方法来获得总的记忆量。我该怎么做呢?

    更新:

    14 回复  |  直到 8 年前
        1
  •  184
  •   Danny Beckett    10 年前

    添加对的引用 Microsoft.VisualBasic using Microsoft.VisualBasic.Devices;

    这个 ComputerInfo 类具有您需要的所有信息。

        2
  •  64
  •   Ryan Lundy    16 年前

    static ulong GetTotalMemoryInBytes()
    {
        return new Microsoft.VisualBasic.Devices.ComputerInfo().TotalPhysicalMemory;
    }
    
        3
  •  63
  •   Kissaki    4 年前

    windowsapi函数 GlobalMemoryStatusEx 可以使用p/invoke调用:

      [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(NativeMethods.MEMORYSTATUSEX));
         }
      }
    
    
      [return: MarshalAs(UnmanagedType.Bool)]
      [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
      static extern bool GlobalMemoryStatusEx([In, Out] MEMORYSTATUSEX lpBuffer);
    

    然后使用类似于:

    ulong installedMemory;
    MEMORYSTATUSEX memStatus = new MEMORYSTATUSEX();
    if( GlobalMemoryStatusEx( memStatus))
    { 
       installedMemory = memStatus.ullTotalPhys;
    }
    

    TotalPhysicalMemory Win32_ComputerSystem

        4
  •  37
  •   sstan    9 年前

    这里的所有答案,包括被接受的答案,都将给出RAM的总量 供使用。这可能就是OP想要的。

    但是如果你想得到 安装 拉姆,那你就给警察打个电话 GetPhysicallyInstalledSystemMemory 作用

    从“备注”部分的链接:

    GetPhysicallyInstalledSystemMemory 函数从计算机的SMBIOS固件表中检索物理安装的RAM量。这可能与客户报告的金额不同 函数,该函数将MemoryStatuex结构的ullTotalPhys成员设置为可供操作系统使用的物理内存量。 因为BIOS和某些驱动程序可能会将内存保留为内存映射设备的I/O区域,从而使操作系统和应用程序无法使用内存。

    [DllImport("kernel32.dll")]
    [return: MarshalAs(UnmanagedType.Bool)]
    static extern bool GetPhysicallyInstalledSystemMemory(out long TotalMemoryInKilobytes);
    
    static void Main()
    {
        long memKb;
        GetPhysicallyInstalledSystemMemory(out memKb);
        Console.WriteLine((memKb / 1024 / 1024) + " GB of RAM installed.");
    }
    
        5
  •  31
  •   grendel    14 年前

    如果您碰巧使用的是Mono,那么您可能有兴趣知道Mono 2.8(将于今年晚些时候发布)将有一个性能计数器,用于报告Mono运行的所有平台(包括Windows)上的物理内存大小。您可以使用以下代码段检索计数器的值:

    using System;
    using System.Diagnostics;
    
    class app
    {
       static void Main ()
       {
           var pc = new PerformanceCounter ("Mono Memory", "Total Physical Memory");
           Console.WriteLine ("Physical RAM (bytes): {0}", pc.RawValue);
       }
    }
    

    here .

        6
  •  16
  •   BRAHIM Kamel    5 年前

    .net Core 3.0 没有必要使用 PInvoke 平台以获取可用的物理内存。这个 GC GC.GetGCMemoryInfo 返回一个 GCMemoryInfo Struct TotalAvailableMemoryBytes 作为一种财产。此属性返回垃圾收集器的总可用内存。(与MemoryStatuex的值相同)

    var gcMemoryInfo = GC.GetGCMemoryInfo();
    installedMemory = gcMemoryInfo.TotalAvailableMemoryBytes;
    // it will give the size of memory in MB
    var physicalMemory = (double) installedMemory / 1048576.0;
    
        7
  •  15
  •   zgerd    10 年前

    另一种方法是使用.NET System.Management查询工具:

    string Query = "SELECT Capacity FROM Win32_PhysicalMemory";
    ManagementObjectSearcher searcher = new ManagementObjectSearcher(Query);
    
    UInt64 Capacity = 0;
    foreach (ManagementObject WniPART in searcher.Get())
    {
        Capacity += Convert.ToUInt64(WniPART.Properties["Capacity"].Value);
    }
    
    return Capacity;
    
        8
  •  7
  •   Nilan Niyomal    10 年前

    using Microsoft.VisualBasic.Devices;
    

    然后,用户只需使用以下代码

        private void button1_Click(object sender, EventArgs e)
        {
            getAvailableRAM();
        }
    
        public void getAvailableRAM()
        {
            ComputerInfo CI = new ComputerInfo();
            ulong mem = ulong.Parse(CI.TotalPhysicalMemory.ToString());
            richTextBox1.Text = (mem / (1024*1024) + " MB").ToString();
        }
    
        9
  •  5
  •   basgys    8 年前
    // use `/ 1048576` to get ram in MB
    // and `/ (1048576 * 1024)` or `/ 1048576 / 1024` to get ram in GB
    private static String getRAMsize()
    {
        ManagementClass mc = new ManagementClass("Win32_ComputerSystem");
        ManagementObjectCollection moc = mc.GetInstances();
        foreach (ManagementObject item in moc)
        {
           return Convert.ToString(Math.Round(Convert.ToDouble(item.Properties["TotalPhysicalMemory"].Value) / 1048576, 0)) + " MB";
        }
    
        return "RAMsize";
    }
    
        10
  •  5
  •   jrh rahul    8 年前

    你可以使用WMI。找到了一个狙击手。

    Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" _ 
    & strComputer & "\root\cimv2") 
    Set colComputer = objWMIService.ExecQuery _
    ("Select * from Win32_ComputerSystem")
    
    For Each objComputer in colComputer 
      strMemory = objComputer.TotalPhysicalMemory
    Next
    
        11
  •  2
  •   jrh rahul    8 年前

    ManagementQuery )适用于Windows XP及更高版本:

    private static string ManagementQuery(string query, string parameter, string scope = null) {
        string result = string.Empty;
        var searcher = string.IsNullOrEmpty(scope) ? new ManagementObjectSearcher(query) : new ManagementObjectSearcher(scope, query);
        foreach (var os in searcher.Get()) {
            try {
                result = os[parameter].ToString();
            }
            catch {
                //ignore
            }
    
            if (!string.IsNullOrEmpty(result)) {
                break;
            }
        }
    
        return result;
    }
    

    用法:

    Console.WriteLine(BytesToMb(Convert.ToInt64(ManagementQuery("SELECT TotalPhysicalMemory FROM Win32_ComputerSystem", "TotalPhysicalMemory", "root\\CIMV2"))));
    
        12
  •  1
  •   Soroush Falahati    6 年前

    与.Net和Mono兼容(使用Win10/FreeBSD/CentOS测试)

    使用 ComputerInfo PerformanceCounter s用于Mono,作为.Net的备份:

    using System;
    using System.Diagnostics;
    using System.Runtime.InteropServices;
    using System.Security;
    
    public class SystemMemoryInfo
    {
        private readonly PerformanceCounter _monoAvailableMemoryCounter;
        private readonly PerformanceCounter _monoTotalMemoryCounter;
        private readonly PerformanceCounter _netAvailableMemoryCounter;
    
        private ulong _availablePhysicalMemory;
        private ulong _totalPhysicalMemory;
    
        public SystemMemoryInfo()
        {
            try
            {
                if (PerformanceCounterCategory.Exists("Mono Memory"))
                {
                    _monoAvailableMemoryCounter = new PerformanceCounter("Mono Memory", "Available Physical Memory");
                    _monoTotalMemoryCounter = new PerformanceCounter("Mono Memory", "Total Physical Memory");
                }
                else if (PerformanceCounterCategory.Exists("Memory"))
                {
                    _netAvailableMemoryCounter = new PerformanceCounter("Memory", "Available Bytes");
                }
            }
            catch
            {
                // ignored
            }
        }
    
        public ulong AvailablePhysicalMemory
        {
            [SecurityCritical]
            get
            {
                Refresh();
    
                return _availablePhysicalMemory;
            }
        }
    
        public ulong TotalPhysicalMemory
        {
            [SecurityCritical]
            get
            {
                Refresh();
    
                return _totalPhysicalMemory;
            }
        }
    
        [SecurityCritical]
        [DllImport("Kernel32", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern void GlobalMemoryStatus(ref MEMORYSTATUS lpBuffer);
    
        [SecurityCritical]
        [DllImport("Kernel32", CharSet = CharSet.Auto, SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        private static extern bool GlobalMemoryStatusEx(ref MEMORYSTATUSEX lpBuffer);
    
        [SecurityCritical]
        private void Refresh()
        {
            try
            {
                if (_monoTotalMemoryCounter != null && _monoAvailableMemoryCounter != null)
                {
                    _totalPhysicalMemory = (ulong) _monoTotalMemoryCounter.NextValue();
                    _availablePhysicalMemory = (ulong) _monoAvailableMemoryCounter.NextValue();
                }
                else if (Environment.OSVersion.Version.Major < 5)
                {
                    var memoryStatus = MEMORYSTATUS.Init();
                    GlobalMemoryStatus(ref memoryStatus);
    
                    if (memoryStatus.dwTotalPhys > 0)
                    {
                        _availablePhysicalMemory = memoryStatus.dwAvailPhys;
                        _totalPhysicalMemory = memoryStatus.dwTotalPhys;
                    }
                    else if (_netAvailableMemoryCounter != null)
                    {
                        _availablePhysicalMemory = (ulong) _netAvailableMemoryCounter.NextValue();
                    }
                }
                else
                {
                    var memoryStatusEx = MEMORYSTATUSEX.Init();
    
                    if (GlobalMemoryStatusEx(ref memoryStatusEx))
                    {
                        _availablePhysicalMemory = memoryStatusEx.ullAvailPhys;
                        _totalPhysicalMemory = memoryStatusEx.ullTotalPhys;
                    }
                    else if (_netAvailableMemoryCounter != null)
                    {
                        _availablePhysicalMemory = (ulong) _netAvailableMemoryCounter.NextValue();
                    }
                }
            }
            catch
            {
                // ignored
            }
        }
    
        private struct MEMORYSTATUS
        {
            private uint dwLength;
            internal uint dwMemoryLoad;
            internal uint dwTotalPhys;
            internal uint dwAvailPhys;
            internal uint dwTotalPageFile;
            internal uint dwAvailPageFile;
            internal uint dwTotalVirtual;
            internal uint dwAvailVirtual;
    
            public static MEMORYSTATUS Init()
            {
                return new MEMORYSTATUS
                {
                    dwLength = checked((uint) Marshal.SizeOf(typeof(MEMORYSTATUS)))
                };
            }
        }
    
        private struct MEMORYSTATUSEX
        {
            private uint dwLength;
            internal uint dwMemoryLoad;
            internal ulong ullTotalPhys;
            internal ulong ullAvailPhys;
            internal ulong ullTotalPageFile;
            internal ulong ullAvailPageFile;
            internal ulong ullTotalVirtual;
            internal ulong ullAvailVirtual;
            internal ulong ullAvailExtendedVirtual;
    
            public static MEMORYSTATUSEX Init()
            {
                return new MEMORYSTATUSEX
                {
                    dwLength = checked((uint) Marshal.SizeOf(typeof(MEMORYSTATUSEX)))
                };
            }
        }
    }
    
        13
  •  0
  •   Roman Starkov    10 年前

    没有人提到过 GetPerformanceInfo 然而 PInvoke signatures 都有。

    • 承诺限制
    • 委员会讲话
    • 物理总量
    • 系统缓存
    • 内核分页
    • 每页记录条数

    PhysicalTotal 是OP要查找的内容,尽管该值是页数,所以要转换为字节,请乘以 PageSize

        14
  •  0
  •   hardkoded    7 年前

    .NIT对其可访问的内存总量有一个限制。有一个百分比,然后xp中的2GB是硬上限。

    同样在64位模式下,有一定百分比的内存可以从系统中使用,因此我不确定您是否可以要求全部内存,或者是否有专门的防范措施。

        15
  •  -3
  •   SuMeeT ShaHaPeTi    12 年前
    /*The simplest way to get/display total physical memory in VB.net (Tested)
    
    public sub get_total_physical_mem()
    
        dim total_physical_memory as integer
    
        total_physical_memory=CInt((My.Computer.Info.TotalPhysicalMemory) / (1024 * 1024))
        MsgBox("Total Physical Memory" + CInt((My.Computer.Info.TotalPhysicalMemory) / (1024 * 1024)).ToString + "Mb" )
    end sub
    */
    
    
    //The simplest way to get/display total physical memory in C# (converted Form http://www.developerfusion.com/tools/convert/vb-to-csharp)
    
    public void get_total_physical_mem()
    {
        int total_physical_memory = 0;
    
        total_physical_memory = Convert.ToInt32((My.Computer.Info.TotalPhysicalMemory) /  (1024 * 1024));
        Interaction.MsgBox("Total Physical Memory" + Convert.ToInt32((My.Computer.Info.TotalPhysicalMemory) / (1024 * 1024)).ToString() + "Mb");
    }
    
        16
  •  -3
  •   Alberico Francesco    3 年前

    var ram = new ManagementObjectSearcher("select * from Win32_PhysicalMemory") .Get().Cast<ManagementObject>().First();

    |

    var a = Convert.ToInt64(ram["Capacity"]) / 1024 / 1024 / 1024;

    (richiede System.management.dll come riferimento,测试su C#con Framework 4.7.2)


    ulong memory() { return new Microsoft.VisualBasic.Devices.ComputerInfo().TotalPhysicalMemory; }

    |

    var b = Convert.ToDecimal(memory()) / 1024 / 1024 / 1024;

    (richiede Microsoft.VisualBasics.dll come riferimento,testato su C#Framework 4.7.2)

    在“b”中使用“b”和“b”两个字母,在GB中使用“b”和“b”两个字母