处理IO.File.ReadAllLines

时间:2014-04-27 00:59:05

标签: vb.net dispose streamreader .net

我正在阅读非常大的文本文件(6-10 MB)。我正在将文本文件拆分为多个新文本文件。有共同的"标题"和"页脚"在"阅读"我将存储为将在以后调用的变量的文本文件。我无法弄清楚如何正确处理IO.File.ReadAllLines。我担心如果我没有妥善处理它,这将留在记忆中。

Text.Dispose或Text.Close无效。

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()

稍后在程序中,我将启动另一个StreamReader,并希望避免冲突和内存资源问题。我是新编码所以要温柔!谢谢!

' 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()

1 个答案:

答案 0 :(得分:1)

你不需要处理它。它返回一个托管字符串数组,其生命周期由垃圾收集器管理。在内部,File.ReadAllLines正在处理它创建的底层本机文件句柄,以便为您读取所有行。