locked
Substitute for PerformanceCounter RRS feed

  • Question

  • Hi, I am currently using the PerformanceCounter object to retrieve the available RAM on the computer. However, PerformanceCounter can be disabled on some computers. I know it can be re-enabled by editing the registry, but is there another way that is guaranteed to retrieve the available RAM without manually editing anything? Thank you.
    Monday, March 23, 2009 2:36 AM

Answers

  • I am not familiar with disabling of PerformanceCounter, but you can P/Invoke GlobalMemoryStatusEx instead.

    using System;  
    using System.Collections.Generic;  
    using System.ComponentModel;  
    using System.Runtime.InteropServices;  
    using System.Text;  
     
    namespace ConsoleApplication1  
    {  
        class Program  
        {  
            [DllImport("kernel32.dll", SetLastError = true)]  
            [return: MarshalAs(UnmanagedType.Bool)]  
            private static extern bool GlobalMemoryStatusEx(ref MEMORYSTATUSEX lpBuffer);  
     
            [StructLayout(LayoutKind.Sequential)]  
            private struct 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;  
            }  
     
            static void Main(string[] args)  
            {  
                MEMORYSTATUSEX status = new MEMORYSTATUSEX();  
                status.dwLength = (uint)Marshal.SizeOf(typeof(MEMORYSTATUSEX));  
     
                if (!GlobalMemoryStatusEx(ref status))  
                    throw new Win32Exception();  
     
                Console.WriteLine("Total physical: {0}", status.ullTotalPhys);  
                Console.WriteLine("Avail physical: {0}", status.ullAvailPhys);  
                Console.WriteLine("Total pages   : {0}", status.ullTotalPageFile);  
                Console.WriteLine("Avail pages   : {0}", status.ullAvailPageFile);  
                Console.ReadLine();  
            }  
        }  
    }  
     
    • Proposed as answer by Harry Zhu Wednesday, March 25, 2009 12:40 AM
    • Marked as answer by Harry Zhu Friday, March 27, 2009 6:39 AM
    Monday, March 23, 2009 11:33 PM