File I/O in a multiuser environment has presented problems for me for a while. i have resorted the the not so ideal method of making very short references to files, keeping them open for the least amount of time possible. this works ok for my needs, but if there is a Class level method for file I/O which can help in multiuser context i would be very keen to see more (hint )
Hi mate
I'm actually talking about creating your own class to handle the file I/O but then utilise the class's terminate event to ensure that it gets closed properly. Here's an example which should hopefully illustrate the idea. I'm assuming that the file I/O you're referring to is the normal Open, Close, Print, Write, etc but let me know if not.
Insert a class module and name it CFile and paste this code:
Code:
Option Explicit
Private Const mlCLASS_ERROR As Long = vbObjectError + 1
Private miFreeFile As Integer
Private mbFileOpen As Boolean
Public Function OpenFile(sFilename As String)
On Error GoTo ErrHandler
If Not mbFileOpen Then
miFreeFile = FreeFile()
Open sFilename For Output As #miFreeFile
mbFileOpen = True
Else
Err.Raise mlCLASS_ERROR, , "File already open."
End If
ExitFunction:
Exit Function
ErrHandler:
Err.Raise mlCLASS_ERROR, , Err.Description
End Function
Public Sub WriteLine(sValue As String)
If Not mbFileOpen Then
Err.Raise mlCLASS_ERROR, , "File not open."
Else
Print #miFreeFile, sValue
End If
End Sub
Public Sub CloseFile()
Close #miFreeFile
mbFileOpen = False
End Sub
Private Sub Class_Terminate()
On Error Resume Next
CloseFile
End Sub
Then to test it use something like this:
Code:
Sub TestIt()
'Test of CFile class
On Error GoTo ErrHandler
Dim oFile As CFile
Set oFile = New CFile
oFile.OpenFile ("C:\temp\hello.txt")
oFile.WriteLine "test file written by CFile object..."
oFile.WriteLine "another line..."
oFile.WriteLine "closing now..."
oFile.CloseFile
MsgBox "File succesfully created.", vbInformation, "CFile Test"
ExitSub:
Exit Sub
ErrHandler:
MsgBox Err.Description, vbExclamation, "An error occurred."
End Sub
With this technique the file gets closed regardless of whether your code errors out (e.g. trying to create a file on a non-existent folder) or if you don't explicitly call the CloseFile method. You can test this by putting a Msgbox in the class's CloseFile method and then commenting out the oFile.CloseFile.
HTH
DK