Question Close & reclose

solfinker

Well-known member
Joined
Aug 6, 2013
Messages
71
Programming Experience
Beginner
Hello.
From time to time I have an error message that says: "File already in use" and I suppose it has sth to do with the fact that I have priorly used it and it has not been properly closed.

The code I use is the following, and I suppose that tmpstream.Close() is not sufficient to close my file.

VB.NET:
Try
            Dim strline() As String
            Dim fName1 As String = str1 
 Dim TextLine() As String
            Dim SplitLine() As String
            If System.IO.File.Exists(fName1) = True Then
                Dim tmpstream As StreamReader = File.OpenText(fName1)
                TextLine = File.ReadAllLines(fName1)
                Dim lineCount = TextLine.Length
                SplitLine = Split(TextLine(0), ",")
                For X = 0 To 49
                    strline = TextLine(lineCount - X - 1).Split(",") 'we read the last 50 lines of the file
                    For Y = 0 To 5 
                        P1(49 - X, Y) = strline(Y)
                    Next
                Next
                tmpstream.Close() 'close reader
            Else
                MsgBox("File doesn't exist")
            End If
Catch ex As Exception
            MsgBox(ex.Message)
End Try

Thank you for your advice.
 
Thank you.
So, I get rid of the "tmpstream". And I use the "Using Statement" instead of the "Try... Catch" for a couple of days and see what happens.
 
v.gr.

VB.NET:
Dim strline() As String
 Dim fName1 As String = str1 
 Dim TextLine() As String
 Dim SplitLine() As String
Using reader as streamreader = New StreamReader(fName1)
            If System.IO.File.Exists(fName1) = True Then
                TextLine = File.ReadAllLines(fName1)
                Dim lineCount = TextLine.Length
                SplitLine = Split(TextLine(0), ",")
                For X = 0 To 49
                    strline = TextLine(lineCount - X - 1).Split(",") 'we read the last 50 lines of the file
                    For Y = 0 To 5 
                        P1(49 - X, Y) = strline(Y)
                    Next
                Next
                
            Else
                MsgBox("File doesn't exist")
            End If

End using
 
Repeat: You don't use 'reader' so get rid of it.
 
Thank you.
And which is the resource I am USING and must be released? FileStream? Because I think I am not using it, even though perhaps I should
 
None, File.ReadAllLines method will open/read/close file before returning the lines.
 
Back
Top