C# =CharSet.Auto,SetLastError=true)] 私有静态外部void GlobalMemoryStatus(ref MEMORYSTATUS lpBuffer); [证券评论] [DllImport(“内核32”,CharSet=CharSet.Auto,SetLastError=true)] [返回:Marshallas(UnmanagedType.Bool)] 私有静态外部bool GlobalMemoryStatusEx(ref MEMORYSTATUSEX lpBuffer); [证券评论] 私有无效刷新() { 尝试 { if(_monotalMemoryCounter!=null&&u monovailableMemoryCounter!=null) { _totalPhysicalMemory=(ulong)u monottalMemoryCounter.NextValue(); _availablePhysicalMemory=(ulong)_monovailableMemoryCounter.NextValue(); } else if(Environment.OSVersion.Version.Major0) { _availablePhysicalMemory=memoryStatus.dwAvailPhys; _totalPhysicalMemory=memoryStatus.dwTotalPhys; } else if(\u netAvailableMemoryCounter!=null) { _availablePhysicalMemory=(ulong)\u netAvailableMemoryCounter.NextValue(); } } 其他的 { var memoryStatusEx=memoryStatusEx.Init(); if(GlobalMemoryStatusEx(ref memoryStatusEx)) { _availablePhysicalMemory=MemoryStatuex.ullAvailPhys; _totalPhysicalMemory=MemoryStatuex.ullTotalPhys; } else if(\u netAvailableMemoryCounter!=null) { _availablePhysicalMemory=(ulong)\u netAvailableMemoryCounter.NextValue(); } } } 抓住 { //忽略 } } 私有结构内存状态 { 私人单位长度; 内部单元数据存储器负载; 内部单元DWT; 内部单元dwAvailPhys; 内部uint dwTotalPageFile; 内部uint dwAvailPageFile; 内部单元DWT; 内部单位有效虚拟; 公共静态MEMORYSTATUS Init() { 返回新的MEMORYSTATUS { dwLength=已检查((uint)封送处理大小(typeof(MEMORYSTATUS))) }; } } 私有结构内存状态 { 私人单位长度; 内部单元数据存储器负载; 内乌龙; 内部乌隆乌拉韦希; 内部ulong文件; 内部ulong ullAvailPageFile; 内部乌龙集团; 内部ulong ullAvailVirtual; 内部ulong UllAvailablesTendedVirtual; 公共静态MemoryStatuex Init() { 返回新的MemoryStatutex { dwLength=已检查((uint)封送处理大小(typeof(memoryStatuex))) }; } } }

C# =CharSet.Auto,SetLastError=true)] 私有静态外部void GlobalMemoryStatus(ref MEMORYSTATUS lpBuffer); [证券评论] [DllImport(“内核32”,CharSet=CharSet.Auto,SetLastError=true)] [返回:Marshallas(UnmanagedType.Bool)] 私有静态外部bool GlobalMemoryStatusEx(ref MEMORYSTATUSEX lpBuffer); [证券评论] 私有无效刷新() { 尝试 { if(_monotalMemoryCounter!=null&&u monovailableMemoryCounter!=null) { _totalPhysicalMemory=(ulong)u monottalMemoryCounter.NextValue(); _availablePhysicalMemory=(ulong)_monovailableMemoryCounter.NextValue(); } else if(Environment.OSVersion.Version.Major0) { _availablePhysicalMemory=memoryStatus.dwAvailPhys; _totalPhysicalMemory=memoryStatus.dwTotalPhys; } else if(\u netAvailableMemoryCounter!=null) { _availablePhysicalMemory=(ulong)\u netAvailableMemoryCounter.NextValue(); } } 其他的 { var memoryStatusEx=memoryStatusEx.Init(); if(GlobalMemoryStatusEx(ref memoryStatusEx)) { _availablePhysicalMemory=MemoryStatuex.ullAvailPhys; _totalPhysicalMemory=MemoryStatuex.ullTotalPhys; } else if(\u netAvailableMemoryCounter!=null) { _availablePhysicalMemory=(ulong)\u netAvailableMemoryCounter.NextValue(); } } } 抓住 { //忽略 } } 私有结构内存状态 { 私人单位长度; 内部单元数据存储器负载; 内部单元DWT; 内部单元dwAvailPhys; 内部uint dwTotalPageFile; 内部uint dwAvailPageFile; 内部单元DWT; 内部单位有效虚拟; 公共静态MEMORYSTATUS Init() { 返回新的MEMORYSTATUS { dwLength=已检查((uint)封送处理大小(typeof(MEMORYSTATUS))) }; } } 私有结构内存状态 { 私人单位长度; 内部单元数据存储器负载; 内乌龙; 内部乌隆乌拉韦希; 内部ulong文件; 内部ulong ullAvailPageFile; 内部乌龙集团; 内部ulong ullAvailVirtual; 内部ulong UllAvailablesTendedVirtual; 公共静态MemoryStatuex Init() { 返回新的MemoryStatutex { dwLength=已检查((uint)封送处理大小(typeof(memoryStatuex))) }; } } },c#,memory,performancecounter,C#,Memory,Performancecounter,对于使用.net Core 3.0的用户,无需使用PInvoke平台来获取可用的物理内存。GC类添加了一个新方法GC.GetGCMemoryInfo,该方法返回一个GCMemoryInfo结构,并将TotalAvailableMemoryBytes作为属性。此属性返回垃圾收集器的总可用内存。(与MemoryStatuex的值相同) var ram=new ManagementObjectSearcher(“从Win32_PhysicalMemory中选择*).Get().Cast().First

对于使用
.net Core 3.0
的用户,无需使用
PInvoke
平台来获取可用的物理内存。
GC
类添加了一个新方法
GC.GetGCMemoryInfo
,该方法返回一个
GCMemoryInfo结构,并将
TotalAvailableMemoryBytes
作为属性。此属性返回垃圾收集器的总可用内存。(与MemoryStatuex的值相同)


var ram=new ManagementObjectSearcher(“从Win32_PhysicalMemory中选择*).Get().Cast().First()

|

var a=Convert.ToInt64(ram[“容量])/1024/1024/1024

(richiede System.management.dll come riferimento,测试su C#con Framework 4.7.2)

以GB为单位呈现的“a”字ram总计中的问题程序


ulong memory(){返回新的Microsoft.VisualBasic.Devices.ComputerInfo().TotalPhysicalMemory;}

|

var b=Convert.ToDecimal(memory())/1024/1024/1024

(richiede Microsoft.VisualBasics.dll come riferimento,testato su C#Framework 4.7.2)

在“b”中使用“b”和“b”两个字母,在GB中使用“b”和“b”两个字母



这究竟是为什么被否决的?投票支持!这是最简单的方法,是的,您可以从C#+1中执行此操作。有些人不喜欢从C#中引用Microsoft.VisualBasic命名空间,即使它实际上只是另一个程序集,是作为其他所有程序的一部分安装的。在Windows7 64位、8gb ram上返回负垃圾值。这就是你为什么被否决的原因?对于任何对使用(新ComputerInfo())心存疑虑的人来说。TotalPhysicalMemory,它在一个内存比这个还要多的系统上工作得很好。它的返回类型是无符号长的,因此如果没有(无效)cast.var totalGBRam=Convert.ToInt32((new ComputerInfo().TotalPhysicalMemory/(Math.Pow(1024,3)))+0.5),负数是不可能的;那不管用。。。long ramuse=(long)stat.TotalPhysical;long ramavailable=(long)stat.AvailablePhysical;long ramtotal=RamaAvailable+ramuse;整数百分比=(整数)((浮动)ramuse/ramtotal*100);百分比告诉我“70”,总数不断变化,给或拿100。应该是72%代码可以工作,只是您不需要使用“NativeMethods”来获取对象的大小,您可以这样说:
this.dwLength=(uint)Marshal.SizeOf(this)和它的工作原理是一样的(我在使用NativeMethods时遇到了问题,所以这个修复现在可以工作了)。“NativeMethods”是该类型的名称空间。如果愿意,可以更改对SizeOf的调用。@Corelgott无用,因为它提供了最新信息?我的意思是,每次我查看天气频道,它都会提供不同的信息,但我不会说它完全无用。我甚至不知道如果这个函数没有返回可能不同的信息,您希望它做什么
counter.CategoryName = "Memory";
counter.Countername = "Available MBytes";
  [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;
}
static ulong GetTotalMemoryInBytes()
{
    return new Microsoft.VisualBasic.Devices.ComputerInfo().TotalPhysicalMemory;
}
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);
   }
}
/*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");
}
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();
    }
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;
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"))));
[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.");
}
// 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";
}
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)))
            };
        }
    }
}
var gcMemoryInfo = GC.GetGCMemoryInfo();
installedMemory = gcMemoryInfo.TotalAvailableMemoryBytes;
// it will give the size of memory in MB
var physicalMemory = (double) installedMemory / 1048576.0;