I've inherited some c++ code for formatting USB flash drives, but it fails if the flash disk is in a bad state and I can't figure out why (or what makes the flash disk state bad).
If the flash drive (usb fob) has a partition but no file system, and it's in the funny state, my WMI format code fails with error 11 "no media in drive", but using the Windows Disk Management widget the drive formats just fine. And after formatting with the Disk Management widget, my WMI code will also format it fine from that point forward. My code will even format it fine after removing the partition using diskpart and re-creating the partition, assuming it was formatted with the Disk Management widget prior to removing the partition.
I can reproduce this with multiple brands and sizes of USB flash drive. To put it into the funny state, I first copy data to the drive, then remove and recreate the partition using diskpart. Afterwords sometimes the drive will be in the funny state where I cannot format it, and sometimes I can format it fine. Always the Disk Management widget can format it fine. Running my code "As administrator" makes no difference.
Can anyone help me figure out what the Disk Management widget is doing differently, or what I'm missing? I'm at a loss as to why it doesn't work when it doesn't work, so I really don't know what to try next for a solution.
Here's what I'm doing in code (C++):
/* Parameters are set as follows */
pInParInst->FileSystem = exFat
pInParInst->QuickFormat = true
pInParInst->Label = "MyDisk"
IWbemServices::ExecMethod ("\\PC-NAME\ROOT\CIMV2:Win32_Volume.DeviceID="\\\\?\\Volume{f110cf76-ff7b-11e2-8697-005056c00008}\\"",
"Format",
0,
NULL,
pInParInst,
&pOutPar,
NULL);
/* When checking the result: */
pOutPar->Get(L"ReturnValue", 0, &vtRetVal, NULL, 0);
vtRetVal.vt = 3 /* type is int */
vtRetVal.intVal = 11 /* No media in drive */
Here is what the flash disk looks like in Windows Disk Management widget before formatting it: