C# 你如何获得计算机的总内存量?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/105031/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do you get total amount of RAM the computer has?
提问by Joel
Using C#, I want to get the total amount of RAM that my computer has. With the PerformanceCounter I can get the amount of Available ram, by setting:
使用 C#,我想获得我的计算机拥有的 RAM 总量。使用 PerformanceCounter,我可以通过设置获得可用内存的数量:
counter.CategoryName = "Memory";
counter.Countername = "Available MBytes";
But I can't seem to find a way to get the total amount of memory. How would I go about doing this?
但我似乎无法找到获得总内存量的方法。我该怎么做呢?
Update:
更新:
MagicKat: I saw that when I was searching, but it doesn't work - "Are you missing an assembly or reference?". I've looked to add that to the References, but I don't see it there.
MagicKat:我在搜索时看到了,但它不起作用-“您是否缺少程序集或参考?”。我想把它添加到参考文献中,但我没有在那里看到它。
采纳答案by Philip Rieck
The p/invoke way EDIT: Changed to GlobalMemoryStatusEx to give accurate results (heh)
p/invoke 方式编辑:更改为 GlobalMemoryStatusEx 以提供准确的结果(呵呵)
[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);
Then use like:
然后使用像:
ulong installedMemory;
MEMORYSTATUSEX memStatus = new MEMORYSTATUSEX();
if( GlobalMemoryStatusEx( memStatus))
{
installedMemory = memStatus.ullTotalPhys;
}
Or you can use WMI (managed but slower) to query "TotalPhysicalMemory" in the "Win32_ComputerSystem" class.
或者,您可以使用 WMI(托管但速度较慢)来查询“Win32_ComputerSystem”类中的“TotalPhysicalMemory”。
Editfixed code per comment from joel-llamaduck.blogspot.com
编辑来自 joel-llamaduck.blogspot.com 的每条评论的固定代码
回答by DevelopingChris
.NIT has a limit to the amount of memory it can access of the total. Theres a percentage, and then 2 GB in xp was the hard ceiling.
.NIT 对它可以访问的总内存量有限制。有一个百分比,然后 xp 中的 2 GB 是硬上限。
You could have 4 GB in it, and it would kill the app when it hit 2GB.
你可以有 4 GB,当它达到 2 GB 时它会杀死应用程序。
Also in 64 bit mode, there is a percentage of memory you can use out of the system, so I'm not sure if you can ask for the whole thing or if this is specifically guarded against.
同样在 64 位模式下,您可以在系统外使用一定比例的内存,所以我不确定您是否可以要求整个事情,或者是否特别防范。
回答by MagicKat
Add a reference to Microsoft.VisualBasic
and a using Microsoft.VisualBasic.Devices;
.
添加对Microsoft.VisualBasic
和 的引用using Microsoft.VisualBasic.Devices;
。
The ComputerInfo
class has all the information that you need.
该ComputerInfo
课程包含您需要的所有信息。
回答by CodeRot
You could use WMI. Found a snippit.
你可以使用 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
回答by Ryan Lundy
Add a reference to Microsoft.VisualBasic.dll, as someone mentioned above. Then getting total physical memory is as simple as this (yes, I tested it):
添加对 Microsoft.VisualBasic.dll 的引用,正如上面提到的那样。然后获得总物理内存就这么简单(是的,我测试过):
static ulong GetTotalMemoryInBytes()
{
return new Microsoft.VisualBasic.Devices.ComputerInfo().TotalPhysicalMemory;
}
回答by grendel
If you happen to be using Mono, then you might be interested to know that Mono 2.8 (to be released later this year) will have a performance counter which reports the physical memory size on all the platforms Mono runs on (including Windows). You would retrieve the value of the counter using this code snippet:
如果您碰巧使用 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);
}
}
If you are interested in C code which provides the performance counter, it can be found here.
如果您对提供性能计数器的 C 代码感兴趣,可以在此处找到。
回答by SuMeeT ShaHaPeTi
/*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");
}
回答by Nilan Niyomal
you can simply use this code to get those information, just add the reference
您可以简单地使用此代码来获取这些信息,只需添加引用
using Microsoft.VisualBasic.Devices;
and the simply use the following code
并且只需使用以下代码
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();
}
回答by zgerd
Another way to do this, is by using the .NET System.Management querying facilities:
另一种方法是使用 .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;
回答by Roman Starkov
Nobody has mentioned GetPerformanceInfoyet. PInvoke signaturesare available.
还没有人提到GetPerformanceInfo。PInvoke 签名可用。
This function makes the following system-wide information available:
此功能使以下系统范围的信息可用:
- CommitTotal
- CommitLimit
- CommitPeak
- PhysicalTotal
- PhysicalAvailable
- SystemCache
- KernelTotal
- KernelPaged
- KernelNonpaged
- PageSize
- HandleCount
- ProcessCount
- ThreadCount
- 提交总数
- 提交限制
- 提交峰值
- 体力合计
- 物理可用
- 系统缓存
- 内核总数
- 内核分页
- 内核非分页
- 页面大小
- 句柄计数
- 进程数
- 线程数
PhysicalTotal
is what the OP is looking for, although the value is the number of pages, so to convert to bytes, multiply by the PageSize
value returned.
PhysicalTotal
是 OP 正在寻找的,尽管该值是页数,因此要转换为字节,请乘以PageSize
返回的值。