Solved

How to check if file is locked

Posted on 2002-05-28
9
406 Views
Last Modified: 2012-05-04
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".
0
Comment
Question by:ASP_Ray
  • 4
  • 3
  • 2
9 Comments
 
LVL 142

Expert Comment

by:Guy Hengel [angelIII / a3]
ID: 7039421
As far as I know do the Office applications store the user into their files when opening the file...
0
 
LVL 16

Expert Comment

by:Richie_Simonetti
ID: 7040027
could you use an error handler?
0
 
LVL 1

Author Comment

by:ASP_Ray
ID: 7040414
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.
0
 
LVL 142

Expert Comment

by:Guy Hengel [angelIII / a3]
ID: 7041075
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.

CHeers
0
6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

 
LVL 1

Author Comment

by:ASP_Ray
ID: 7044454
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"?
0
 
LVL 16

Accepted Solution

by:
Richie_Simonetti earned 100 total points
ID: 7044929
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




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


0
 
LVL 1

Author Comment

by:ASP_Ray
ID: 7065815
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.
0
 
LVL 16

Expert Comment

by:Richie_Simonetti
ID: 7065820
Thanks for "A" grade but what could you use, Angel's suggestion or mine?, i don't understand.
0
 
LVL 1

Author Comment

by:ASP_Ray
ID: 7071276
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.
0

Featured Post

Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

Join & Write a Comment

Introduction In a recent article (http://www.experts-exchange.com/A_7811-A-Better-Concatenate-Function.html) for the Excel community, I showed an improved version of the Excel Concatenate() function.  While writing that article I realized that no o…
Introduction While answering a recent question (http://www.experts-exchange.com/Q_27402310.html) in the VB classic zone, I wrote some VB code in the (Office) VBA environment, rather than fire up my older PC.  I didn't post completely correct code o…
Get people started with the process of using Access VBA to control Outlook using automation, Microsoft Access can control other applications. An example is the ability to programmatically talk to Microsoft Outlook. Using automation, an Access applic…
This lesson covers basic error handling code in Microsoft Excel using VBA. This is the first lesson in a 3-part series that uses code to loop through an Excel spreadsheet in VBA and then fix errors, taking advantage of error handling code. This l…

743 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now