• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 588
  • Last Modified:

How to check if file is locked

Can anyone tell me how to check if a file is locked by an application for write access and how to check which user locked it?  Excel does this.  If you try to open a file already opened, it will tell you that the file is "locked for editing" by "...".

All I can do right now is to try to open the file and trap error number 70, "Permission denied".
  • 4
  • 3
  • 2
1 Solution
Guy Hengel [angelIII / a3]Billing EngineerCommented:
As far as I know do the Office applications store the user into their files when opening the file...
Richie_SimonettiIT OperationsCommented:
could you use an error handler?
ASP_RayAuthor Commented:
I'm not sure what the comments from angelll and Richie Simonetti mean so let me restate my question.  I want to know how, from my program, to check if a file is locked by another program because the other program is editing the file.  If I could find out as well which user is using the application which locked the file, that would be nice too.  If you want, say, to delete a file, you must do more than just check if the file exists to avoid a run-time error.  You must also check if the file is locked.  Right now I'm using a workaround to check if the file is locked.  I try to open the file with the VB's Open statement and then check for error number 70.  I do it as follows:

  On Error Resume Next
  iFileNumber = FreeFile
  Open sFileSpec For Input As iFileNumber
  If Err.Number = 70 Then
    'Permission to open is denied
    MsgBox Err.Description
  End If
  Close iFileNumber

Actually, in practice, you would check
"If Err.Number <> 0" but this code is to illustrate what I mean.  

My previous comment about Excel is this.  If you try to open an Excel file on a server, if that file is already opened anywhere on the network, Excel will tell you that the file is locked and will tell you which usere is using the application which locked the file.  Don't get hung up on Excel though, I just used this as an example of ultimately what I would like to do.

Hope this clarifies thinks.  Please continue to comment.
Cloud Class® Course: CompTIA Healthcare IT Tech

This course will help prep you to earn the CompTIA Healthcare IT Technician certification showing that you have the knowledge and skills needed to succeed in installing, managing, and troubleshooting IT systems in medical and clinical settings.

Guy Hengel [angelIII / a3]Billing EngineerCommented:
Hi ASP_Ray:
I did fully understand your problem, and even if you choose Excel as sample, it is a special case, as I know that Excel (as the other MS Office products) store the information of who has openend the file in the file itself, so that other Excel users can get notified of this when trying to open the same file.

This is not implemented for the mass of normal files, as no other application does store this information in their files...

So ultimately, you have to do the same way, either storing the information in the file itself or a secondary file besides... There is no way except checking the error as you showed, and using that method there is no way of telling who opened the file.

ASP_RayAuthor Commented:
Thanks Angellll.  I'm sorry about the delay in answering but my ISP, MSN, was down all day yesterday.  

Now just one last clarification.  You already addressed it but I just want to emphasize.  Are you saying there is no direct way to check if a file is locked?  No Win32 API function?  I can only try to open the file and check for errors, which doesn't even directly return that the file is locked, just a general "permission denied"?
Richie_SimonettiIT OperationsCommented:
Could you try this?
'from MSDN:

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

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.

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();
         // If the open was successful, close the file.

      // 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.
         lclose (hFile)
      End If

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

   End Function

ASP_RayAuthor Commented:
Thanks for all the comments guys, especially you Angelll.  Wish I could split the points with you but since I can't, code always beat no code.  Anyway, keep up the good work guys.
Richie_SimonettiIT OperationsCommented:
Thanks for "A" grade but what could you use, Angel's suggestion or mine?, i don't understand.
ASP_RayAuthor Commented:
Riche, Angel's suggestion was very informative.  It addressed that only office products could tell which user locked the file.  But my primary concern was how to check that file was locked (you can read the question again), and my method, it seemed to me at the time, was only only a work-around.  I wanted a definitive method to do that.  You provided code for this, and even more that, you provided an explanation that had the authority of Microsoft.  That is why I gave you the grade A.  I am now using the code you provided.

Actually I searched the MSDN library for hours on that subject, but I never searched for "sharing violation" or anything similer.  I was searching for text like "locked" etc. so I never came across that article.  Thanks again Richie and lots of thanks to Angellll as well.  Angellll taught me something I am glad to know and you gave me code I am now using.

PS.  I just re-read the last comment I made and I guess since it only spoke to Angelll specifically, you might have thought I was using his suggestion.  SORRY for the confusion.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

  • 4
  • 3
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now