HOWTO: Get and Use a Handle to a Directory

Last reviewed: November 26, 1997
Article ID: Q105306
The information in this article applies to:
  • Microsoft Win32 Application Programming Interface (API) included with: - Microsoft Windows NT versions 3.1, 3.5, 3.51, 4.0

SUMMARY

CreateDirectory() can be used to open a new directory. An existing directory can be opened by calling CreateFile(). To open an existing directory with CreateFile(), it is necessary to specify the flag FILE_FLAG_BACKUP_SEMANTICS. The following code shows how this can be done:

   HANDLE hFile;

   hFile = CreateFile( "c:\\mstools",
              GENERIC_READ | GENERIC_WRITE,
              FILE_SHARE_READ | FILE_SHARE_WRITE,
              NULL,
              OPEN_EXISTING,
              FILE_FLAG_BACKUP_SEMANTICS,
              NULL
           );
   if( hFile == INVALID_HANDLE_VALUE )
      MessageBox( NULL, "CreateFile() failed", NULL, MB_OK );

The handle obtained can be used to obtain information about the directory or to set information about the directory. For example:

   BY_HANDLE_FILE_INFORMATION fiBuf;
   FILETIME ftBuf;
   SYSTEMTIME stBuf;
   char msg[40];

   GetFileInformationByHandle( hFile, &fiBuf );
   FileTimeToLocalFileTime( &fiBuf.ftLastWriteTime, &ftBuf );
   FileTimeToSystemTime( &ftBuf, &stBuf );
   wsprintf( msg, "Last write time is %d:%d  %d/%d/%d",
      stBuf.wHour,stBuf.wMinute,stBuf.wMonth,stBuf.wDay,stBuf.wYear );
   MessageBox( NULL, msg, NULL, MB_OK );

MORE INFORMATION

Opening directories with CreateFile is not supported on Windows 95.

This code does not work on Win32s, because MS-DOS does not support opening a directory. If you are looking for the creation time of a directory, use FindFirstFile(), because it works on all platforms.

Keywords          : BseFileio
Version           : winnt:3.1,3.5,3.51,4.0;
Platform          : winnt
Issue type        : kbhowto


================================================================================


THE INFORMATION PROVIDED IN THE MICROSOFT KNOWLEDGE BASE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. MICROSOFT DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING THE WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL MICROSOFT CORPORATION OR ITS SUPPLIERS BE LIABLE FOR ANY DAMAGES WHATSOEVER INCLUDING DIRECT, INDIRECT, INCIDENTAL, CONSEQUENTIAL, LOSS OF BUSINESS PROFITS OR SPECIAL DAMAGES, EVEN IF MICROSOFT CORPORATION OR ITS SUPPLIERS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. SOME STATES DO NOT ALLOW THE EXCLUSION OR LIMITATION OF LIABILITY FOR CONSEQUENTIAL OR INCIDENTAL DAMAGES SO THE FOREGOING LIMITATION MAY NOT APPLY.

Last reviewed: November 26, 1997
© 1998 Microsoft Corporation. All rights reserved. Terms of Use.