HOWTO: Determine If a File Is Already Open

Last reviewed: August 1, 1997
Article ID: Q172240
The information in this article applies to:
  • Microsoft Win32 Application Programming Interface (API) included with: - Microsoft Visual Basic Learning, Professional, and Enterprise Editions

         for Windows, version 5.0
    

SUMMARY

You can open a file multiple times in different applications as long as one application does not have exclusive access to the file. There may be times when your application needs to have exclusive access to a file, and the application may need to determine whether it is already open. This article explains how to determine whether a file is already open. It also contains two versions of a function you can use to detect whether a file is already open.

MORE INFORMATION

The only sure way your application can determine whether it can open a file exclusively is by trying to open the file. If you are able to open the file, your application has exclusive access. Otherwise, it doesn't.

If your application needs to determine whether a file is already open, it should attempt to open the file for exclusive-sharing access. If a sharing violation occurs during the attempt, the file is already open. If the attempt causes a different error, such as access denied or file not found, then your application will not be able to tell whether the file is already open.

The function described here is called IsFileAlreadyOpen, declared as:

   BOOL IsFileAlreadyOpen(char *filename); // In C/C++...
   Function IsFileAlreadyOpen(Filename As String) As BOOLEAN // In VB...

If this function returns TRUE, then the file is already open. It determines that the file is already open only if it gets ERROR_SHARING_VIOLATION when it attempts to open the file.

It will return FALSE in the following conditions:

  • The file is not already open.
  • The calling application does not have access to the file due to NTFS security.
  • The file does not exist.

You should check if the file exists before calling the function to eliminate the possibility of the latter condition.

Sample Code: C/C++ version of IsFileAlreadyOpen

   BOOL IsFileAlreadyOpen(char *filename)
   {
      HFILE theFile = HFILE_ERROR;
      DWORD lastErr  = NO_ERROR;

      // Attempt to open the file exclusively.
      theFile = _lopen(filename, OF_READ | OF_SHARE_EXCLUSIVE);

      if (theFile == HFILE_ERROR)
         // Save last error...
         lastErr = GetLastError();
      else
         // If the open was successful, close the file.
         _lclose(theFile);

      // Return TRUE if there is a sharing-violation.
      return ((theFile == HFILE_ERROR) &&
              (lastErr == ERROR_SHARING_VIOLATION));
   }

Sample Code: Microsoft Visual Basic version of IsFileAlreadyOpen

   ' Declaration for APIs used by our function...
   Private Declare Function lopen Lib "kernel32" Alias "_lopen" (ByVal
   lpPathName As String, ByVal iReadWrite As Long) As Long
   Private Declare Function GetLastError Lib "kernel32" () As Long
   Private Declare Function lclose Lib "kernel32" Alias "_lclose" (ByVal
   hFile As Long) As Long

   ' Our Function...
   Function IsFileAlreadyOpen(Filename As String) As Boolean
      Dim hFile As Long
      Dim lastErr As Long

      ' Initialize file handle and error variable.
      hFile = -1
      lastErr = 0

      ' Open for for read and exclusive sharing.
      hFile = lopen(Filename, &H10)

      ' If we couldn't open the file, get the last error.
      If hFile = -1 Then
         lastErr = Err.LastDllError
      ' Make sure we close the file on success.
      Else
         lclose (hFile)
      End If

      ' Check for sharing violation error.
      If (hFile = -1) And (lastErr = 32) Then
         IsFileAlreadyOpen = True
      Else
         IsFileAlreadyOpen = False
      End If

   End Function

REFERENCES

For more information about shared modes, see:

Product name Help, version n.n; search on: "word or phrase"; topic: topic.

read the Win32 SDK Help on the _lopen() API. It lists and describes the various modes available and in particular, OF_SHARE_EXCLUSIVE.

Keywords          : BseFileio kbcode
Version           : WINDOWS:5.0; WINDOWS NT:
Platform          : NT WINDOWS
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: August 1, 1997
© 1998 Microsoft Corporation. All rights reserved. Terms of Use.