如何在 C# 中获取特定进程的磁盘使用率 (MB/s)?
我能够像这样获得 CPU 使用率和 RAM 使用率:
var cpu = new PerformanceCounter("Process", "% Processor Time", ProcessName, true)
var ram = new PerformanceCounter("Process", "Working Set - Private", ProcessName, true);
Console.WriteLine($"CPU = {cpu.NextValue() / Environment.ProcessorCount} %");
Console.WriteLine($"RAM = {ram.NextValue() / 1024 / 1024} MB");
但我找不到任何与磁盘使用情况相关的信息。
如任务管理器中所示:
最佳答案
♻️ 方法
This API will tell you total number of I/O operations as well as total bytes.
You can call GetProcessIoCounters to get overall disk I/O data per process - you'll need to keep track of deltas and converting to time-based rate yourself.
所以,基于this C# tutorial你可以按照这些思路做一些事情:
struct IO_COUNTERS
{
public ulong ReadOperationCount;
public ulong WriteOperationCount;
public ulong OtherOperationCount;
public ulong ReadTransferCount;
public ulong WriteTransferCount;
public ulong OtherTransferCount;
}
[DllImport("kernel32.dll")]
private static extern bool GetProcessIoCounters(IntPtr ProcessHandle, out IO_COUNTERS IoCounters);
public static void Main()
{
IO_COUNTERS counters;
Process[] processes = Process.GetProcesses();
foreach(Process process In processes)
{
try {
GetProcessIoCounters(process.Handle, out counters);
console.WriteLine("\"" + process.ProcessName + " \"" + " process has read " + counters.ReadTransferCount.ToString("N0") + "bytes of data.");
} catch (System.ComponentModel.Win32Exception ex) {
}
}
console.ReadKey();
}
使用 this将其转换为 VB.NET
但是 (System.ComponentModel.Win32Exception ex) 发生了
System.ComponentModel.Win32Exception (0x80004005): Access is denied
at System.Diagnostics.ProcessManager.OpenProcess(Int32 processId, Int32 access, Boolean throwIfExited)
at System.Diagnostics.Process.GetProcessHandle(Int32 access, Boolean throwIfExited)
at System.Diagnostics.Process.OpenProcessHandle(Int32 access)
at System.Diagnostics.Process.get_Handle()
at taskviewerdisktest.Form1.Main() in C:\...\source\repos\taskviewerdisktest\taskviewerdisktest\Form1.vb:line 32
有些进程似乎真的很难访问..好消息是在我的情况下它们并不多(250 个中有 15 个左右)..
⚠️ 免责声明:这更像是一种“解决方案”而不是“解决方案”的方法
♻️ 其他方法和引用
关于c# - 在 C# 中获取特定进程的磁盘使用情况,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53560561/