Determining a computer's maximum hard drive data transfer rate programmatically with C#

好久不见. 提交于 2019-12-07 02:15:31

问题


I have written a small WPF widget using C# that displays the current CPU activity, RAM used and disk activity as three small percentage type bars. I have used the following PerformanceCounters for this: (diskCounter PerformanceCounter returns current total disk activity in bytes per second)

private void InitialisePerformanceCounters()
{
    cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total", true);
    totalRam = (int)(new Microsoft.VisualBasic.Devices.ComputerInfo().TotalPhysicalMemory / 1024 / 1024);
    ramCounter = new PerformanceCounter("Memory", "Available MBytes");
    diskCounter = new PerformanceCounter("PhysicalDisk", "Disk Bytes/sec", "_Total", true);
}

The problem is that although I have discovered how to get the total available RAM to calculate a used percentage from, I cannot find out how to read the disk's 'theoretical' maximum data transfer rate. I need this to calculate the percentage of disk transfer rate used. Any help would be greatly appreciated.


回答1:


The only way to do this would be to test it yourself. You could do something like this at the beginning of your application:

byte[] data = new byte[1024];

string path = System.IO.Path.GetTempFileName();

int bytesPerSecond = 0;

using (System.IO.FileStream fs = new System.IO.FileStream(path, System.IO.FileMode.Create))
{
    System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();

    watch.Start();

    for (int i = 0; i < 1024; i++) fs.Write(data, 0, data.Length);

    fs.Flush();

    watch.Stop();

    bytesPerSecond = (int)((data.Length * 1024) / watch.Elapsed.TotalSeconds);
}

System.IO.File.Delete(path);

This does, however, assume that the Temp directory is on the disk in question. If not, you'll have to create a path on the disk you want to measure. Note that this is measuring write speed, not read speed.

This is somewhat contrived since 1MB is not much data to write, but you could try it with a larger amount of data; the concept is the same.




回答2:


Try to use WMI api, also LINQ to WMI can be helpful.




回答3:


I Don't know any way to obtain the maximum data transfer rate of a HD, but with WMI you can obtain the intarface of the hard disk (USB,IDE...). You could use the maximum data transfer rate of the interface and reffers your percentage to it.

Also, I'm going to leave a link here to a little article about obtain info frm the HD using WMI, with source code. LINK



来源:https://stackoverflow.com/questions/3150956/determining-a-computers-maximum-hard-drive-data-transfer-rate-programmatically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!