Search code examples
c++winapiusbcorruption

Win32 C++ detect USB-drive corruption


I am working on a kiosk application using Windows 7 as the OS, and Win32 C++ to detect and manage USB drives. We just found a bug where, if a USB is corrupt in some way, the OS will pop up the following dialog which is hidden behind the kiosk application and therefore never gets shown.

image of the dialog

When a user goes to copy to this drive, the application crashes.

I have been looking for a way to detect when I get a USB DBT_DEVICEARRIVAL notification whether or not this newly added USB is corrupt, but haven't come up with any good possibilities. What I have come up with is the possibility of calling DeviceIoControl() and passing IOCTL_DISK_GET_PARTITION_INFO as the control code, since the PARTITION_INFORMATION structure returned can tell me whether the partition type is recognized or not. But this doesn't necessarily tell me whether the USB is corrupt. I assume this is more likely to tell whether this is a recognized NTFS format, as opposed to a format written by a Linux or Mac system.

Can anyone tell me how I could go about detecting corruption in a newly added USB drive, so that I can take the necessary next steps?

One more thing. I've tried to purposefully create a corruption on my USB drive so that I can emulate the issue found by our user, but Win7 seems to be smart enough to stop me from doing that. Does anyone know of a way to create a corrupted USB drive for test purposes?


Solution

  • You're incorrectly relating this to USB. Instead, it's a volume flag. Obtaining this status is possible via WMI, for example. See Win32_LogicalDisk.VolumeDirty - if TRUE, then disk requires chkdsk. Once you know the volume requires repairing, you can run chkdsk.exe from your program.

    You can also use fsutil dirty query f: to check if volume requires repair, and fsutil dirty set f: to manually set this bit. That also allows you to make a test USB.

    On some computers, Scan&Fix popup may be disabled. Still, if you set dirty bit, Scan&Fix will show computers where it's not disabled.

    PS: I think you should figure why your app crashes and fix that as well. I believe that is a separate problem in your app.