C#で利用可能な空きメモリの容量を取得する方法

コンピュータ

Windows限定ですが空きメモリを取得するコードを調べました。

プロジェクトの作成

cd (mkdir UserMemorySpace01 -Force)
dotnet new console -f net8.0
dotnet add package System.Diagnostics.PerformanceCounter

ファイル名:Program.cs

public static class UserMemoryHelper
{
    public static ulong GetAvailableMemoryInBytes()
    {
        if (OperatingSystem.IsWindows())
        {
            var pc = new System.Diagnostics.PerformanceCounter("Memory", "Available Bytes");
            return (ulong)pc.NextValue();
        }

        // Linux/macOS では別手段が必要。ここでは簡略化
        return ulong.MaxValue;
    }    
}

class Program
{
    static void Main()
    {
        ulong mem = UserMemoryMannager.GetAvailableMemoryInBytes();
        Console.WriteLine($"空き容量:{mem}");
        // 結果
        // 空き容量:48219348992
    }
}

実行してみると数秒待たされて結果が返る感じなので、アプリの最初などで実行するような使い方が良いかもしれません。

コメント