1

我有这个程序,但是当它尝试访问 FIRST 时出现问题... 我需要分离驱动程序并且只获得 C:\ 的总大小。当程序在 if... 处停止时,表示驱动器尚未准备好。我能做些什么?

class Program
{
    static void Main(string[] args)
    {
        string mainHD = Path.GetPathRoot(Environment.GetFolderPath(Environment.SpecialFolder.System));

        GetTotalFreeSpace(mainHD);

        DriveInfo[] drives = DriveInfo.GetDrives();
        foreach (DriveInfo drive in drives)
        {
            if (drive.VolumeLabel != @"C:\")
            {
                //There are more attributes you can use.
                //Check the MSDN link for a complete example.
                string drivesname = drive.Name;
                Console.WriteLine(drivesname);
                if (drive.IsReady) Console.WriteLine(drive.TotalSize);
            }
        }
        Console.ReadLine();
    }

    private static long GetTotalFreeSpace(string driveName)
    {
        foreach (DriveInfo drive in DriveInfo.GetDrives())
        {
            if (drive.IsReady && drive.Name == driveName)
            {
                return drive.TotalSize;
            }
        }
        return -1;
    }
}
}
4

3 回答 3

1

问题不清楚。按照代码,这是旋转/等待可能是最佳选择的罕见情况之一。有两个调用Drive.IsReady都可以从旋转/等待中受益。后者可以像...

private static long GetTotalFreeSpace(string driveName)
    {
        foreach (DriveInfo drive in DriveInfo.GetDrives())
        {
            if(!Drive.IsReady)
                //spin wait implemented however you deem appropriate.  Maybe sleep a second or so
            if (drive.Name == driveName)
            {
                return drive.TotalSize;
            }
        }
        return -1;
    }

二、根据MSDN:

IsReady 指示驱动器是否准备就绪。例如,它指示 CD 是否在 CD 驱动器中或可移动存储设备是否已准备好进行读/写操作。如果您不测试驱动器是否准备好,并且它还没有准备好,使用 DriveInfo 查询驱动器将引发 IOException。

我建议您也添加一些逻辑来处理IOException

于 2014-03-06T20:54:28.260 回答
1

看起来你应该在检查drive.IsReady之前进行测试drive.VolumeLabel

查看MSDN 示例

尝试这个:

foreach (DriveInfo drive in drives)
{
    if (drive.IsReady && drive.VolumeLabel != @"C:\")
    {
        //There are more attributes you can use.
        //Check the MSDN link for a complete example.
        string drivesname = drive.Name;
        Console.WriteLine(drivesname);
        Console.WriteLine(drive.TotalSize);
    }
}

虽然这可能是 C: 驱动器未准备好的问题,但也可能是存在 A: 或 B: 软盘驱动器的情况,在这种情况下,继续检查IsReady直到它准备好可能不是一个好方法主意。

于 2014-03-06T20:55:07.253 回答
0

我似乎记得这是尝试访问没有磁盘的“A:”驱动器的问题。即使您实际上在 A: 上没有驱动器,很多机器还是会在那里报告它。

于 2014-03-06T20:56:06.757 回答