Question File access problem...

ianr900

Member
Joined
Jul 13, 2006
Messages
18
Location
UK
Programming Experience
3-5
I can't quite find the right way to implement what i am trying to acheive here. Would appreciate any suggestions.

I want to save a string of text to a file every 1.4 seconds or so, and each day at midnight I want to create a new file for the days log data so I keep the file size down. The file stays open the whole time so that it is ready to accept data from several different forms which call a function (SaveToVoltsLogFile(str)), so I open it at module level like this:

VB.NET:
Dim fsVlogStream As New FileStream(EVENT_LOG_PATH & VOLTS_LOG_FILENAME & DateString & ".ip", FileMode.Append, FileAccess.Write, FileShare.Read)
Dim swVlogWriter As New StreamWriter(fsVlogStream)
Now each time I call a function SaveToVoltsLogFile(str), the str data gets saved to the file:
VB.NET:
Friend Sub SaveToVoltsLogFile(ByVal str As String)
        swVlogWriter.WriteLine(str)
        swVlogWriter.Flush()
End Sub
But by opening it this way, I cannot call a sub to close it and open a new file for the next day because putting the Dims into a sub means that the file is out of scope to other subs/functions, so my Save... sub won't work!
So, what I think i need is a seperate sub to open the file, another sub to close it, and another to write the str data. But how do I do this and keep the file in scope to all subs?
 

Robert_Zenz

Well-known member
Joined
Jun 3, 2008
Messages
503
Location
Vienna, Austria
Programming Experience
3-5
VB.NET:
Private logDate As Date = Date.Now
Private fsVlogStream As FileStream = Nothing
Private swVlogWriter As StreamWriter = Nothing

Friend Sub OpenLog()
      If Me.swVlogWriter IsNot Nothing Then Me.swVlogWriter.Close()
      If Me.fsVlogStream IsNot Nothing Then Me.fsVlogStream.Close()

      Me.logDate = Date.Now()

      Me.fsVlogStream = New FileStream(EVENT_LOG_PATH & VOLTS_LOG_FILENAME & Me.logDate.ToString("yyMMdd") & ".ip", FileMode.Append, FileAccess.Write, FileShare.Read)
      Me.swVlogWriter = New StreamWriter(fsVlogStream)
End Sub

Friend Sub SaveToVoltsLogFile(ByVal str As String)
      If Me.logDate.Day <> Date.Now().Day Then Me.OpenLog()

      swVlogWriter.WriteLine(str)
      swVlogWriter.Flush()
End Sub
Something like this?

Bobby
 

ianr900

Member
Joined
Jul 13, 2006
Messages
18
Location
UK
Programming Experience
3-5
Working...

Thanks Bobby. That works great!
 
Top Bottom