r/visualbasic • u/Jooniar • May 23 '12
Stubborn StreamReader
Hey guys,
I've got a bit of trouble here, this component of my code writes an integer to a text file on close and then writes it to an integer when the form loads.
The problem I'm having is that the "Process cannot access the file because it is being used by another process" error.
Now I've put it down to my load streamreader, even though I've included the streamreader.close() line it doesn't actually process this line. It only reads the line before it and proceeds to open the form.
Here's my code:
Private Sub Main_FormClosing(ByVal sender As System.Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
Dim sw_QuoteNo As StreamWriter
Dim sFileName As String
Dim iRecords As Integer
iRecords = lbxQuoteNumber.Items.Count
sFileName = Application.StartupPath & "\QuoteEnd.txt"
sw_QuoteNo = New StreamWriter(sFileName, True)
If File.Exists(sFileName) Then
sw_QuoteNo.WriteLine(iQuoteEnd)
Else
MsgBox("The file was not found.")
End If
sw_QuoteNo.Close()
End Sub
Private Sub frmQuoteSystem_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim sr_QuoteNumber As StreamReader
Dim sFileName As String
Dim sLine As String
sFileName = Application.StartupPath & "\QuoteEnd.txt"
sr_QuoteNumber = New StreamReader(sFileName, True)
iQuoteEnd = sr_QuoteNumber.ReadLine
sr_QuoteNumber.Close()
End SubObviously, one is the form load sub and the other is the closing sub.
Some clarity would be much appreciated, I've been working on this for far too long to no avail.
(I do have other streamreader/writers but they're triggered with a button)
1
u/Jooniar May 23 '12
Worked it out! If anyone else runs into this issue, I had to use "Using".
e.g.
Same for my writer.