求助:使用C#获取物理内存量

fengq802 2012-05-23 11:31:51
需要获取系统的总物理内存量及剩余内存量。
参考了sno888在2008-9-8回复“准确获取内存”的内容,编写的代码如下:
ManagementClass memo = new ManagementClass("Win32_OperatingSystem");
ManagementObjectCollection memoVol = memo.GetInstances();
double capacity = 0;
foreach (ManagementObject mo in memoVol)
{
capacity += ((Math.Round(Int64.Parse(mo.Properties["FreePhysicalMemory"].Value.ToString()) / 1024 / 1024 / 1024.0, 1)));
}
运行上述代码,得到的capacity值为0,是何原因?请教各位高手^^
...全文
143 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
cnfixit 2012-05-23
  • 打赏
  • 举报
回复

MEMORYSTATUS ms = new MEMORYSTATUS();
NativeMethods.GlobalMemoryStatus(out ms);
MessageBox.Show((ms.dwTotalPhys/1024/1024).ToString());

[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public struct MEMORYSTATUS
{

/// DWORD->unsigned int
public uint dwLength;

/// DWORD->unsigned int
public uint dwMemoryLoad;

/// SIZE_T->ULONG_PTR->unsigned int
public uint dwTotalPhys;

/// SIZE_T->ULONG_PTR->unsigned int
public uint dwAvailPhys;

/// SIZE_T->ULONG_PTR->unsigned int
public uint dwTotalPageFile;

/// SIZE_T->ULONG_PTR->unsigned int
public uint dwAvailPageFile;

/// SIZE_T->ULONG_PTR->unsigned int
public uint dwTotalVirtual;

/// SIZE_T->ULONG_PTR->unsigned int
public uint dwAvailVirtual;
}

public partial class NativeMethods
{

/// Return Type: void
///lpBuffer: LPMEMORYSTATUS->_MEMORYSTATUS*
[System.Runtime.InteropServices.DllImportAttribute("kernel32.dll", EntryPoint = "GlobalMemoryStatus")]
public static extern void GlobalMemoryStatus([System.Runtime.InteropServices.OutAttribute()] out MEMORYSTATUS lpBuffer);

}
cnfixit 2012-05-23
  • 打赏
  • 举报
回复
GlobalMemoryStatus

试试整个

111,126

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Creator Browser
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧