开发者

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

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 transfe开发者_运维知识库r rate. I need this to calculate the percentage of disk transfer rate used. Any help would be greatly appreciated.


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.


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜