Question

I am reading very large text files (6-10 MB). I am splitting the text files in to multiple new text files. There is common "header" and "footer" in the "read" text file that I will store as variable to be called at later time. I can't figure out how to properly dispose of IO.File.ReadAllLines. I'm concerned this will be held in memory if I don't dispose of it properly.

Text.Dispose or Text.Close isn't valid.

Dim testHeader As String
Dim testSite As String
Dim testStart As String
Dim testStop As String
Dim testTime As String

Dim text() As String = IO.File.ReadAllLines("C:\Users\anobis\Desktop\temp.txt")
testHeader = text(0)
testSite = text(text.Length - 4)
testStart = text(text.Length - 3)
testStop = text(text.Length - 2)
testTime = text(text.Length - 1)
text.dispose()

Later in the program I will be initiating another StreamReader and want to avoid conflicts and memory resource issues. I am new at coding so be gentle! Thanks!

' Open temp.txt with "Using" statement.
Using r As StreamReader = New StreamReader("C:\Users\anobis\Desktop\temp.txt")

    ' Store contents in this String.
    Dim line As String
    line = r.ReadLine

    ' Loop over each line in file, While list is Not Nothing.
    Do While (Not line Is Nothing)
        If line Like (sourceSN.Text + "*") Then  'Substitute in source serial number "xxxxxx*"
            file.WriteLine(line)
        End If
        ' Read in the next line of text file.
        line = r.ReadLine
    Loop

End Using

file.WriteLine(testSite)
file.WriteLine(testStart)
file.WriteLine(testStop)
file.WriteLine(testTime)

' Close transfer.txt file
file.Close()
Was it helpful?

Solution

You don't need to dispose of it. It returns a managed string array, who's lifetime is managed by the garbage collector. Internally, File.ReadAllLines is disposing of the underlying native file handle it created to read all of the lines for you.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top