Phil Carson
Phil Carson

Reputation: 884

C# DriveInfo class causes windows error popup

When using the DriveInfo class occasionally displays a windows message popup:

There is no disk in the drive. Please insert a disk into drive \Device\Harddisk1\DR1

The code that I am working with is fairly standard:

var driveInfos = DriveInfo.GetDrives();
foreach (DriveInfo driveInfo in driveInfos)
{
    if (driveInfo.IsReady &&
        (driveInfo.DriveType == DriveType.Network || driveInfo.DriveType == DriveType.Removable))
        try
        {
            var driveText = string.Format("{0} ({1})", driveInfo.VolumeLabel, driveInfo.Name);

Having had a look on the web it turns out that this is an uncommon error but one that seems be due to environmental issues on the machine (people report it happening when running things like chrome). A lot of people have fixed this by cleaning up old usb references.

The error doesn't actually stop the program from working normally apart from displaying the message. ( And doesn't get trapped in the catch block )

As its a wpf application that is a going to be distributed and run on end users pc's I rather that the message box is not displayed. How can I do this and what are the implications?

Edit:

Further investigation showed that this behavior may be being caused because that the code is being executed through a background worker and two instances of it are running at the same time.

Taking the same code and executing without using a background worker it seems to run without issue.

Upvotes: 1

Views: 783

Answers (1)

Ria
Ria

Reputation: 10347

I tested your code and it runs with no problem. It seems be using driveInfo.IsReady cause your problem, because of it calls for every drives (CD/DVD/...). Check DriveType first and then check IsReady; like this:

if (driveInfo.DriveType == DriveType.Network || 
    driveInfo.DriveType == DriveType.Removable)
    if (driveInfo.IsReady)
    {
       var driveText = string.Format("{0} ({1})",
                                     driveInfo.VolumeLabel, driveInfo.Name);
    }

Upvotes: 2

Related Questions