How can I get the total physical memory in C#?
I am using the GlobalMemoryStatusEx
function to retrieve information about memory, but this function doesn't work correctly. It returns 0 for all properties. I don't think this function works in my Windows 7 environment.
[StructLayout(LayoutKind.Sequential)]
internal struct MEMORYSTATUSEX
{
internal 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;
}
[return: MarshalAs(UnmanagedType.Bool)]
[DllImport("Kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
internal static extern bool GlobalMemoryStatusEx(ref MEMORYSTATUSEX lpBuffer);
private void btnGlobalMemoryStatusEX_Click(object sender, EventArgs e)
{
MEMORYSTATUSEX statEX = new MEMORYSTATUSEX();
GlobalMemoryStatusEx(ref statEX);
double d = (double)statEX.ullTotalPhys;
}
Can anybody tell me where I went wrong with wrong code?
I find my mistake from: http://www.pinvoke.net/default.aspx/kernel32/GlobalMemoryStatusEx.html
I Changed
internal static extern bool GlobalMemoryStatusEx(ref MEMORYSTATUSEX lpBuffer);
To
static extern bool GlobalMemoryStatusEx([In, Out] MEMORYSTATUSEX lpBuffer);
and changed
GlobalMemoryStatusEx(ref statEX);
To
GlobalMemoryStatusEx(statEX);
It work correctly. Tanks
How about:
My.Computer.Info.TotalPhysicalMemory
My.Computer.Info.AvailablePhysicalMemory
If c# you can:
Reference the Microsoft.VisualBasic
assembly.
Then import Microsoft.VisualBasic.Devices
namespace.
And finally use ComputerInfo to get the total physical memory.
int bytesPerMebibyte = (1 << 20); // http://physics.nist.gov/cuu/Units/binary.html
ComputerInfo myCompInfo = new ComputerInfo();
string physicalMemory = "Physical Memory: "
+ (myCompInfo.TotalPhysicalMemory / bytesPerMebibyte) + " MB";
you can use this templates:
long memory = Process.GetCurrentProcess().PeakVirtualMemorySize64;
And another properties with names Peak*64
You forgot to set statEX.dwLength
before calling GlobalMemoryStatusEx
.
MEMORYSTATUSEX statEX = new MEMORYSTATUSEX();
statEX.dwLength = (uint)Marshal.SizeOf(typeof(MEMORYSTATUSEX));
GlobalMemoryStatusEx(ref statEX);
精彩评论