ManagementObject返回错误的TotalSectors

时间:2018-10-13 12:29:46

标签: c#

此代码给出了错误的扇区数。
我有3个磁盘:

0.   468.862.128 sectors - program shows     7.887.915  
1. 3.907.029.168 sectors - program shows 3.907.024.065  
2.     7.897.088 sectors - program shows   468.857.025



    int driveCount = 0;
    try
    {
        ManagementObjectSearcher searcher =
            new ManagementObjectSearcher("root\\CIMV2",
            "SELECT * FROM Win32_DiskDrive");

        foreach (ManagementObject queryObj in searcher.Get())
        {
            if (driveCount == drive)
            {
                var t = queryObj["TotalSectors"];
                return long.Parse(t.ToString());

            }
            driveCount++;
        }
    }
    catch (ManagementException)
    {
        return -1;
    }
    return -1;

看起来像是大小混合在一起,但是值也略有不同

1 个答案:

答案 0 :(得分:0)

循环增量错误

            int driveCount = 0;
            try
            {
                ManagementObjectSearcher searcher =
                    new ManagementObjectSearcher("root\\CIMV2",
                    "SELECT * FROM Win32_DiskDrive");

                driveCount = searcher.Get().Count - 1;
                foreach (ManagementObject queryObj in searcher.Get())
                {
                    if (driveCount == drive)
                    {
                        var t = queryObj["TotalSectors"];
                        return long.Parse(t.ToString());

                    }
                    driveCount--;
                }
            }