使用C#,我想获取计算机拥有的RAM总量。使用PerformanceCounter,我可以通过设置以下内容来获得可用内存的数量:
counter.CategoryName = "Memory";
counter.Countername = "Available MBytes";
但是我似乎找不到找到总内存量的方法。我将如何去做呢?
更新:
MagicKat:我在搜索时看到了,但没有用-“您是否缺少程序集或参考?”。我已经将其添加到参考文献中,但在那儿看不到它。
Answers:
GlobalMemoryStatusEx
可以使用p / invoke调用Windows 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(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;
}
或者,您可以使用WMI(托管的但速度较慢)TotalPhysicalMemory
在Win32_ComputerSystem
类中查询。
this.dwLength = (uint)Marshal.SizeOf(this);
并且它的工作原理相同(我在使用NativeMethods时遇到了麻烦,因此此修复程序现在可以工作)。
向Microsoft.VisualBasic
和添加引用using Microsoft.VisualBasic.Devices;
。
本ComputerInfo
类有你需要的所有信息。
如上所述,添加对Microsoft.VisualBasic.dll的引用。然后,获取总物理内存就这么简单(是的,我测试了它):
static ulong GetTotalMemoryInBytes()
{
return new Microsoft.VisualBasic.Devices.ComputerInfo().TotalPhysicalMemory;
}
这里的所有答案,包括已接受的答案,将为您提供可用的RAM总量。这可能就是OP想要的。
但是,如果您对获取已安装的RAM的数量感兴趣,那么您将需要调用GetPhysicallyInstalledSystemMemory函数。
在链接的“备注”部分中:
该GetPhysicallyInstalledSystemMemory功能从计算机的SMBIOS固件表中检索物理安装的RAM量。这可能与GlobalMemoryStatusEx函数报告的数量不同,后者将MEMORYSTATUSEX结构的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.");
}
如果您碰巧正在使用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);
}
}
如果您对提供性能计数器的C代码感兴趣,可以在此处找到。
另一种方法是使用.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;
Microsoft.VisualBasic.Devices
。并且作为var Capacity = new ManagementObjectSearcher("SELECT Capacity FROM Win32_PhysicalMemory").Get().Cast<ManagementObject>().Sum(x => Convert.ToInt64(x.Properties["Capacity"].Value));
对于正在使用的用户.net Core 3.0
,无需使用PInvoke
平台即可获取可用的物理内存。本GC
类增加了新的方法GC.GetGCMemoryInfo
,它返回一个GCMemoryInfo Struct
带有TotalAvailableMemoryBytes
作为属性。此属性返回垃圾收集器的总可用内存。(与MEMORYSTATUSEX相同的值)
var gcMemoryInfo = GC.GetGCMemoryInfo();
installedMemory = gcMemoryInfo.TotalAvailableMemoryBytes;
// it will give the size of memory in MB
var physicalMemory = (double) installedMemory / 1048576.0;
您只需使用此代码即可获取这些信息,只需添加参考即可
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();
}
// 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";
}
您可以使用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
Set
VB.NET不再需要此VB6代码吗?
此功能(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"))));
BytesToMb
功能从何而来?
与.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)))
};
}
}
}
还没有人提到GetPerformanceInfo。P调用签名可用。
此功能使以下系统范围的信息可用:
PhysicalTotal
OP正在寻找的内容,尽管该值是页面数,所以要转换为字节,请乘以PageSize
返回的值。
.NIT对它可以访问的总内存量有限制。有一个百分比,然后xp中的2 GB是硬上限。
您可能有4 GB,当它达到2GB时它将杀死该应用程序。
同样在64位模式下,您可以在系统外部使用一定百分比的内存,因此我不确定是否可以要求全部内容或是否需要特别注意。
/*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");
}