컴퓨터에있는 총 RAM 양은 어떻게 얻습니까?
C #을 사용하여 내 컴퓨터에있는 총 RAM 양을 얻고 싶습니다. PerformanceCounter를 사용하면 다음을 설정하여 사용 가능한 램의 양을 얻을 수 있습니다.
counter.CategoryName = "Memory";
counter.Countername = "Available MBytes";
그러나 나는 총 메모리 양을 얻는 방법을 찾지 못하는 것 같습니다. 어떻게하면 되나요?
최신 정보:
MagicKat : 검색 할 때 봤는데 작동하지 않습니다. "어셈블리 또는 참조가 누락 되었습니까?". 나는 그것을 References에 추가하려고했지만 거기에는 보이지 않습니다.
p / invoke 방식 EDIT : 정확한 결과를 제공하기 위해 GlobalMemoryStatusEx로 변경되었습니다 (heh).
[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 (관리되지만 느림)를 사용하여 "Win32_ComputerSystem"클래스에서 "TotalPhysicalMemory"를 쿼리 할 수 있습니다.
joel-llamaduck.blogspot.com에서 댓글 당 고정 코드 편집
Microsoft.VisualBasic
및에 대한 참조를 추가합니다 using Microsoft.VisualBasic.Devices;
.
ComputerInfo
클래스는 당신이 필요로하는 모든 정보가 있습니다.
위에서 언급 한 것처럼 Microsoft.VisualBasic.dll에 대한 참조를 추가합니다. 그런 다음 총 물리적 메모리를 얻는 것은 다음과 같이 간단합니다 (예, 테스트했습니다).
static ulong GetTotalMemoryInBytes()
{
return new Microsoft.VisualBasic.Devices.ComputerInfo().TotalPhysicalMemory;
}
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 코드에 관심이 있으시면 여기 에서 찾을 수 있습니다 .
허용되는 답변을 포함하여 여기에있는 모든 답변 은 사용 가능한 총 RAM 용량을 제공 합니다. 그리고 그것은 OP가 원했던 것일 수 있습니다.
그러나 설치된 RAM 의 양을 얻으 려면 GetPhysicallyInstalledSystemMemory 함수를 호출하는 것이 좋습니다.
링크의 비고 섹션에서 :
GetPhysicallyInstalledSystemMemory 기능은 컴퓨터의 SMBIOS 펌웨어 테이블에서 물리적으로 설치 RAM의 양을 검색합니다. 이는 MEMORYSTATUSEX 구조의 ullTotalPhys 멤버를 운영 체제에서 사용할 수있는 실제 메모리 양으로 설정 하는 GlobalMemoryStatusEx 함수에서 보고하는 양과 다를 수 있습니다. 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.");
}
이를 수행하는 또 다른 방법은 .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;
이 코드를 사용하여 정보를 얻을 수 있습니다. 참조를 추가하면됩니다.
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();
}
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
// 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";
}
이 기능 ( 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"))));
아무도 아직 GetPerformanceInfo 를 언급 하지 않았습니다. PInvoke 서명 을 사용할 수 있습니다.
이 기능을 사용하면 다음과 같은 시스템 전체 정보를 사용할 수 있습니다.
- CommitTotal
- CommitLimit
- CommitPeak
- PhysicalTotal
- PhysicalAvailable
- SystemCache
- KernelTotal
- KernelPaged
- KernelNonpaged
- 페이지 크기
- HandleCount
- ProcessCount
- ThreadCount
PhysicalTotal
값은 페이지 수이지만 OP가 찾고있는 것이므로 바이트로 변환하려면 PageSize
반환 된 값을 곱합니다 .
.NIT는 전체에 액세스 할 수있는 메모리 양에 제한이 있습니다. 백분율이 있고 xp의 2GB가 하드 천장이었습니다.
4GB를 사용할 수 있으며 2GB에 도달하면 앱이 종료됩니다.
또한 64 비트 모드에서는 시스템 외부에서 사용할 수있는 메모리의 비율이 있으므로 전체를 요청할 수 있는지 또는 이것이 특별히 보호되는지 확실하지 않습니다.
.Net 및 Mono와 호환 (Win10 / FreeBSD / CentOS에서 테스트 됨)
Mono 및 .Net의 백업으로 ComputerInfo
소스 코드 및 PerformanceCounter
s 사용 :
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)))
};
}
}
}
/*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");
}
참고 URL : https://stackoverflow.com/questions/105031/how-do-you-get-total-amount-of-ram-the-computer-has
'Nice programing' 카테고리의 다른 글
신청서 창을 앞으로 가져 오려면 어떻게해야합니까? (0) | 2020.10.17 |
---|---|
Mongoose를 컴파일 한 후에는 모델을 덮어 쓸 수 없습니다. (0) | 2020.10.17 |
WPF : 응용 프로그램의 중앙에 표시 할 대화 상자 위치를 설정하는 방법은 무엇입니까? (0) | 2020.10.17 |
C ++ 11에서 사용되지 않는 매개 변수 (0) | 2020.10.17 |
쌍을 이루는 순환 파이썬 'for'루프 (0) | 2020.10.17 |