A USB hard drive contains a FAT32 partition. Sometimes the partition has a
drive letter assigned. When the partition has a drive letter, Windows
Explorer and/or some other parts of Windows XP read and cache a portion of
the contents. I write part of the partition myself, so I want to force
Windows to abandon its cached contents.
I call DeviceIoControl several times. FSCTL_LOCK_VOLUME,
FSCTL_DISMOUNT_VOLUME, IOCTL_VOLUME_OFFLINE, IOCTL_VOLUME_ONLINE, and
FSCTL_UNLOCK_VOLUME. All of these succeed. WinIoCtl.h doesn't define
IOCTL_VOLUME_OFFLINE and IOCTL_VOLUME_ONLINE, but MSDN implies that these
are supposed to be available to user mode applications, so I define them
myself and DeviceIoControl reports success.
After that, I have found two ways to do manual operations to force Windows
to abandon its cached contents. One is to use Computer Administrator - Disk
Administrator, remove the drive letter from the partition, and reassign the
drive letter to the partition. The other way is to open a command prompt
and run CHKDSK /F, which finds no errors but which somehow persuades Windows
XP to discard its cache. If I omit the /F then the obsolete contents remain
in the cache, after which Windows proceeds to corrupt the partition and then
the next CHKDSK /F adjusts errors (but lost data remain lost).
Now I want to do this programmatically. I wonder why obsolete contents
remain in the cache after IOCTL_VOLUME_OFFLINE and IOCTL_VOLUME_ONLINE, but
continue trying anyway. I added calls to BroadcastSystemMessage with
DBT_DEVICEREMOVECOMPLETE and DBT_DEVICEARRIVAL. These report success.
Furthermore if Windows Explorer was displaying the partition before these
operations, I can see Windows Explorer respond by removing that partition
from its display, displaying the contents of another partition, and then
restoring the drive letter and icon in the left hand pane though the right
hand pane continues displaying the other partition that it had switched to.
So I think that DBT_DEVICEREMOVECOMPLETE and DBT_DEVICEARRIVAL have some
amount of effect. But when I click on that drive letter in Windows
Explorer, it still displays obsolete cached information, and creating a new
file causes corruption in the partition.
What does it take to force Windows to discard obsolete cached data?