Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Check If File Open By COBOL program Before Using in VB App 2

Status
Not open for further replies.

DesMoinesElvis

Programmer
Nov 9, 2007
3
US
Hello,

I have browsed through Tek-Tips using "Check if File Open" in VB 5&6 Forum as well as extensive searching out on the web for find an answer to my challenge.
In my VB program, I need to first check to see if a COBOL program is done writing data to a file before I go and list the file as ready to use in my app.
thread222-1437198 has a code snippet I tried to use which did not work.
The way I am testing is to open up a simple .TXT file with Notepad, leave it open, then I run my VB program which will search for the file name in a directory and if present list it. I need to further filter to see if the file is open before I throw it as an option in a list box.
Using the code snippets found in the above mentioned thread and other similar snippets on the web, the file opens in my VB app as if it were not already open by Notepad.
Does anyone know how to code in VB to check for a file being already opened by a non-VB program (such as Notepad or a COBOL program)?

Thanks.
Dave
 
I doubt testing with Notepad is any use. It probably opens the file, slurps it all into memory, and closes it.

One way to write your program though might be to probe using a Timer every so often using logic similar to:
Code:
Private Sub Timer1_Timer()
    Dim intFile As Integer
    
    Timer1.Enabled = False
    intFile = FreeFile(1)
    On Error Resume Next
    Open "testfile.txt" For Input Lock Read Write As #intFile
    If Err.Number = 0 Then
        MsgBox "File available"
        Close #intFile
        Unload Me
    Else
        Timer1.Enabled = True
    End If
End Sub
Of course in a real program you'd assign the file number more globally and only close it after reading and processing the data.
 
I'm confused.

Why use 30+ lines of code when 4 lines of VB will do the job (error trap, open exclusive, test for error, close file)? Probably better, because as Randy Birch says in that article:
Assuming then that the application opening the file places a proper lock on the file, this routine will correctly detect if...
... a list of conditions, all of which require that the other program lock the file.

The native-VB alternative above makes no such assumption about how the foreign program has opened the file.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top