c# - 在 C# 中获取特定进程的磁盘使用情况

标签 c# .net

如何在 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");

但我找不到任何与磁盘使用情况相关的信息。

如任务管理器中所示:

et

最佳答案

♻️ 方法

如前所述here ^2 :

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/

相关文章:

c# - 通过 C# 从命令行启动 Weka

JAVA服务提供者SAML2请求-禁用数字签名

c# - 如何从元素中具有相同名称的 xml 文件中获取特定值?

c# - 在 C# 中使用 String.Format 格式化字符串的问题

c# - SM?使用 if exists drop then create 和 no sp_executesql 编写所有 SQL 存储过程的脚本

c# - 如何确定 .NET 中的 CPU 缓存大小?

c# - 如何在保留私钥的同时将 BouncyCaSTLe X509Certificate 转换为 .NET Standard X509Certificate2?

c# - TableLayoutPanel 的控制列属性

c# - 文本框属性

.net - 如何在 .NET 中为 SSL 连接设置测试证书?