🟣 C# / .NET 6+

Backup Page File Usage to JSON (C#)

Snapshots Page File Usage (Win32_PageFileUsage) to a timestamped JSON file via System.Management and System.Text.Json.

By WindowsScripting.com · 1.2 KB
BackupPageFileUsageListToJson.cs
// BackupPageFileUsageListToJson.cs
//
// Snapshots Page File Usage (Win32_PageFileUsage) to a timestamped JSON file.
//
// Requires the System.Management package:
//   dotnet new console -o BackupPageFileUsage
//   dotnet add package System.Management
//   (replace the generated Program.cs with this file, then dotnet run)

using System;
using System.Collections.Generic;
using System.IO;
using System.Management;
using System.Text.Json;

var searcher = new ManagementObjectSearcher("SELECT Name, AllocatedBaseSize, CurrentUsage, PeakUsage FROM Win32_PageFileUsage");
var results = new List<Dictionary<string, object?>>();

foreach (ManagementObject item in searcher.Get())
{
    var row = new Dictionary<string, object?>();
    row["Name"] = item["Name"];
        row["AllocatedBaseSize"] = item["AllocatedBaseSize"];
        row["CurrentUsage"] = item["CurrentUsage"];
        row["PeakUsage"] = item["PeakUsage"];
    results.Add(row);
}

string timestamp = DateTime.Now.ToString("yyyyMMdd-HHmmss");
string outPath = $"pagefileusage-snapshot_{timestamp}.json";
File.WriteAllText(outPath, JsonSerializer.Serialize(results, new JsonSerializerOptions { WriteIndented = true }));

Console.WriteLine($"Snapshot of Page File Usage ({results.Count} items) saved to {outPath}");