65.9K
CodeProject is changing. Read more.
Home

Programmatic Refresh of a File System

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.40/5 (26 votes)

Apr 8, 2005

viewsIcon

65408

How to force the file system to refresh.

Introduction

This is a short article, written after many hours spent on the problem of refreshing a CD file system after burning. At the end, the solution I've found is very very simple, so I've decided to explain it here.

The function

I've used a call to the BroadcastSystemMessage function to send a WM_DEVICECHANGE message to Windows (XP in my case). The function is defined as follows (found on MSDN):

long BroadcastSystemMessage(      
    DWORD dwFlags,
    LPDWORD lpdwRecipients,
    UINT uiMessage,
    WPARAM wParam,
    LPARAM lParam
);

To set the correct parameters for the call, I've initialized a DEV_BROADCAST_VOLUME struct, which is defined as:

typedef struct _DEV_BROADCAST_VOLUME {
  DWORD dbcv_size;
  DWORD dbcv_devicetype;
  DWORD dbcv_reserved;
  DWORD dbcv_unitmask;
  WORD dbcv_flags;
} DEV_BROADCAST_VOLUME, *PDEV_BROADCAST_VOLUME;

The code of my function is here:

bool RefreshFileSystem(char cdrive)
{
  DEV_BROADCAST_VOLUME hdr;
  long result;

  hdr.dbcv_size       =  sizeof(DEV_BROADCAST_VOLUME);
  hdr.dbcv_devicetype =  DBT_DEVTYP_VOLUME;
  hdr.dbcv_reserved = 0;
  cdrive = (char)_totupper(cdrive));  // thanks to Blake Miller
  hdr.dbcv_unitmask = 1 << (cdrive-'A');
  hdr.dbcv_flags  = DBTF_MEDIA;

  result = BroadcastSystemMessage(BSF_NOHANG|BSF_POSTMESSAGE,
                         NULL, WM_DEVICECHANGE, DBT_DEVICEARRIVAL,
                         (LPARAM)&hdr);
  return (result>=0);
}

I've heard of someone who used this kind of a solution but unfortunately the system crashed. I'm trying to find out what has caused the crash.