Solved

Is File Open?

Posted on 1999-01-05
12
826 Views
Last Modified: 2008-02-26
How can I tell if a file is open by another process other than trying to open it and test for an error?
0
Comment
Question by:Neal Hartman
  • 4
  • 2
  • 2
  • +3
12 Comments
 
LVL 14

Expert Comment

by:waty
ID: 1453958
On error goto ERROR_OPEN
nFile = FreeFile
Open sFile For Binary Access Write As #nFile

ERROR_OPEN:
    If Err = 55 then msgbox "File already open"
       
0
 
LVL 4

Expert Comment

by:chabaud
ID: 1453959
Use the API function OpenFile with the OF_EXIST style.

Create Form1 with one button named Open, one button Close and one button Test, then paste this code:

Option Explicit

Private Declare Function OpenFile Lib "kernel32" (ByVal lpFileName As String, lpReOpenBuff As OFSTRUCT, ByVal wStyle As Long) As Long

Private Const OF_SHARE_EXCLUSIVE = &H10
Private Const OF_EXIST = &H4000
Private Const OFS_MAXPATHNAME = 128
Private Const HFILE_ERROR = -1
Private Type OFSTRUCT
        cBytes As Byte
        fFixedDisk As Byte
        nErrCode As Integer
        Reserved1 As Integer
        Reserved2 As Integer
        szPathName(OFS_MAXPATHNAME) As Byte
End Type
Private Const theFile = "D:\tmp\toto.txt"

Private Sub Test_Click()
    Dim ofs As OFSTRUCT
    If OpenFile(theFile, ofs, OF_SHARE_EXCLUSIVE Or OF_EXIST) = HFILE_ERROR Then
        MsgBox "Already opened"
    Else
        MsgBox "not opened"
    End If
End Sub

Private Sub Open_Click()
    Open theFile For Random As #1
End Sub

Private Sub Close_Click()
    Close #1
End Sub

0
 
LVL 3

Expert Comment

by:vikiing
ID: 1453960
Friend Waty: Rmquade is asking for "a process other than trying to open it and test for an error".

Besides that, the code you suggest only checks if file is opened BY THE application ITSELF, and doesn't check for another app..

Rmquade: you have no option. Trying to open the file is the only way to check for it, like this:

    i%=Freefile : on error resume next
    Open <file> for input lock read write as #I% : ser%=err
    close #i%
    If ser%=70 then <permission denied>

If error code is 70, it means file is already opened by an application (perhaps yourself), because you're specifying to block out any other acces, and the only way to achieve that is when file is not in use at all.

   
0
 
LVL 14

Expert Comment

by:waty
ID: 1453961
The code I have done check for an opened file by the current process, by the system, or by another process.

Here is a more complet sample :

On Error Statement Example
This example first uses the On Error GoTo statement to specify the location of an error-handling routine within a procedure. In the example, an attempt to delete an open file generates error number 55. The error is handled in the error-handling routine, and control is then returned to the statement that caused the error. The On Error GoTo 0 statement turns off error trapping. Then the On Error Resume Next statement is used to defer error trapping so that the context for the error generated by the next statement can be known for certain. Note that Err.Clear is used to clear the Err object's properties after the error is handled.

Sub OnErrorStatementDemo()
   On Error GoTo ErrorHandler   ' Enable error-handling routine.
   Open "TESTFILE" For Output As #1   ' Open file for output.
   Kill "TESTFILE"   ' Attempt to delete open
            ' file.
   On Error Goto 0   ' Turn off error trapping.
   On Error Resume Next   ' Defer error trapping.
   ObjectRef = GetObject("MyWord.Basic")   ' Try to start nonexistent
            ' object, then test for
'Check for likely Automation errors.
   If Err.Number = 440 Or Err.Number = 432 Then
      ' Tell user what happened. Then clear the Err object.
      Msg = "There was an error attempting to open the Automation object!"
      MsgBox Msg, , "Deferred Error Test"
      Err.Clear   ' Clear Err object fields
   End If  
Exit Sub      ' Exit to avoid handler.
ErrorHandler:   ' Error-handling routine.
   Select Case Err.Number   ' Evaluate error number.
      Case 55   ' "File already open" error.
         Close #1   ' Close open file.
      Case Else
         ' Handle other situations here...
   End Select
   Resume   ' Resume execution at same line
            ' that caused the error.
End Sub


0
 
LVL 4

Expert Comment

by:chabaud
ID: 1453962
what about my solution using API ?
0
 
LVL 12

Expert Comment

by:mark2150
ID: 1453963
Actually the *BEST* way is to open the file for write and trap the error. If you just *test* the file and do not *GRAB* it for your use then you have no certainty that the result will be valid for any length of time! If you have two competing processes and you do your test and the other does *IT'S* test and you now *BOTH* think you have access to the file and you've reached a condition known as "deadly embrace" where *BOTH* of your processes are cross locked. This is *NOT* the way to safely code multi-user apps.

If you attempt to open the file for WRITE and do *NOT* get the error, then your code can continue to execute, confident that the file is *YOURS ALONE* to manipulate. The requirement "other than trying to open it and test for an error?" will generate *LOCKUPS* in a multi-user environment. The "open it and test for error" method is *CORRECT* and the only way to assure that your code will run no matter how many users are competing for the lock on a standard data file.

M

0
Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 3

Expert Comment

by:vikiing
ID: 1453964
Friend Mark: you've said "you now *BOTH* think you have access to the file and you've reached a condition known as "deadly embrace" where *BOTH* of your processes are cross locked"

That's not right. Because BOTH processes will thing file is free, when both try to re-open, only one will gain access, and the other will die with the error "Permission denied".

The main question here was "How to know if a file is already in use", and not "How to gain exclusive access to a file". If the intended purpose is last one, of course, once file was successfuly opened, it must remain so until the end of the process.

0
 
LVL 1

Author Comment

by:Neal Hartman
ID: 1453965
I guess the I was right in the first place. There are a lot of ways to open and trap for errors but that appears to be the only way.

Thanks Everyone.

0
 
LVL 14

Expert Comment

by:waty
ID: 1453966
As I have posted the answer first would you like to agree my answer?
0
 
LVL 1

Author Comment

by:Neal Hartman
ID: 1453967
Anything for you waty!

0
 
LVL 14

Accepted Solution

by:
waty earned 50 total points
ID: 1453968
On Error Statement Example
This example first uses the On Error GoTo statement to specify the location of an error-handling routine within a procedure. In the example, an attempt to delete an open file generates error number 55. The error is handled in the error-handling routine, and control is then returned to the statement that caused the error. The On Error GoTo 0 statement turns off error trapping. Then the On Error Resume Next statement is used to defer error trapping so that the context for the error generated by the next statement can be known for certain. Note that Err.Clear is used to clear the Err object's properties after the error is handled.

Sub OnErrorStatementDemo()
   On Error GoTo ErrorHandler   ' Enable error-handling routine.
   Open "TESTFILE" For Output As #1   ' Open file for output.
   Kill "TESTFILE"   ' Attempt to delete open
            ' file.
   On Error Goto 0   ' Turn off error trapping.
   On Error Resume Next   ' Defer error trapping.
   ObjectRef = GetObject("MyWord.Basic")   ' Try to start nonexistent
            ' object, then test for
'Check for likely Automation errors.
   If Err.Number = 440 Or Err.Number = 432 Then
      ' Tell user what happened. Then clear the Err object.
      Msg = "There was an error attempting to open the Automation object!"
      MsgBox Msg, , "Deferred Error Test"
      Err.Clear   ' Clear Err object fields
   End If    
Exit Sub      ' Exit to avoid handler.
ErrorHandler:   ' Error-handling routine.
   Select Case Err.Number   ' Evaluate error number.
      Case 55   ' "File already open" error.
         Close #1   ' Close open file.
      Case Else
         ' Handle other situations here...
   End Select
   Resume   ' Resume execution at same line
            ' that caused the error.
End Sub
0
 

Expert Comment

by:BobsExEx
ID: 8265388
None of these solutions work for me.  I have tried every one.
0

Featured Post

Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

Join & Write a Comment

There are many ways to remove duplicate entries in an SQL or Access database. Most make you temporarily insert an ID field, make a temp table and copy data back and forth, and/or are slow. Here is an easy way in VB6 using ADO to remove duplicate row…
I’ve seen a number of people looking for examples of how to access web services from VB6.  I’ve been using a test harness I built in VB6 (using many resources I found online) that I use for small projects to work out how to communicate with web serv…
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…
Get people started with the utilization of class modules. Class modules can be a powerful tool in Microsoft Access. They allow you to create self-contained objects that encapsulate functionality. They can easily hide the complexity of a process from…

708 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

17 Experts available now in Live!

Get 1:1 Help Now