🟣 C# / .NET 6+

Backup Logical Disks to JSON (C#)

Snapshots Logical Disks (Win32_LogicalDisk) to a timestamped JSON file via System.Management and System.Text.Json.

By WindowsScripting.com · 1.3 KB
BackupLogicalDiskListToJson.cs
// BackupLogicalDiskListToJson.cs
//
// Snapshots Logical Disks (Win32_LogicalDisk) to a timestamped JSON file.
//
// Requires the System.Management package:
//   dotnet new console -o BackupLogicalDisk
//   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 DeviceID, VolumeName, Size, FreeSpace, DriveType FROM Win32_LogicalDisk");
var results = new List<Dictionary<string, object?>>();

foreach (ManagementObject item in searcher.Get())
{
    var row = new Dictionary<string, object?>();
    row["DeviceID"] = item["DeviceID"];
        row["VolumeName"] = item["VolumeName"];
        row["Size"] = item["Size"];
        row["FreeSpace"] = item["FreeSpace"];
        row["DriveType"] = item["DriveType"];
    results.Add(row);
}

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

Console.WriteLine($"Snapshot of Logical Disks ({results.Count} items) saved to {outPath}");