WPF获得当前电脑的储存和运存

1.开门见山Show代码:

/// <summary>
/// 总内存(GB)
/// </summary>
public double TotalMemoryGB { get; set; }

/// <summary>
/// 已用内存(GB)
/// </summary>
public double UsedMemoryGB { get; set; }

/// <summary>
/// 总储存(GB)
/// </summary>
public double TotalStorageGB { get; set; }

/// <summary>
/// 已用储存(GB)
/// </summary>
public double UsedStorageGB { get; set; }

//储存
string currentPath = AppDomain.CurrentDomain.BaseDirectory;
var driveLetter = Path.GetPathRoot(currentPath);
DriveInfo drive = new(driveLetter);
TotalStorageGB = Math.Round((double)drive.TotalSize / 1024 / 1024 / 1024, 2);
var UsedBytes = drive.TotalSize - drive.AvailableFreeSpace;
UsedStorageGB = Math.Round((double)UsedBytes / 1024 / 1024 / 1024, 2);

//内存
var _ramCounter = new PerformanceCounter("Memory", "Committed Bytes");
var _ramCounterSize = _ramCounter?.NextValue() ?? 0;
TotalMemoryGB = Math.Round((double)_ramCounterSize / 1024 / 1024 / 1024, 2);
var _availableCounter = new PerformanceCounter("Memory", "Available Bytes");
var _availableCounterSize = _availableCounter?.NextValue() ?? 0;
UsedMemoryGB = TotalMemoryGB - Math.Round((double)_availableCounterSize / 1024 / 1024 / 1024, 2);

*优化:字节数转GB可以单独成工具类 方法

储存可以指定盘符,现在默认是运行程序根目录盘

posted @ 2026-08-10 14:48  Poetindusk  阅读(1)  评论(0)    收藏  举报