读/写大文件VB.NET

时间:2016-11-09 20:16:25

标签: vb.net

我是新用户并且正在努力解决以下问题:

我需要阅读文件并回写一些修改,问题是:

  1. “ReadToEnd”适用于较小的文件[约100MB],一切正常,我喜欢做什么。 但是对于更大尺寸的文件[300 MB +],它会爆炸。
  2. 然后我尝试了“ReadLine”(逐行阅读) 它适用于较小或较大的文件,但需要很长时间才能保存。
  3. 我在“ReadToEnd”和“ReadLine”下面都包含了两个代码 要进行测试,您需要在c:\ temp \ area中创建“100MB-File.txt”和“300MB-File.txt”文件。

    我非常感谢你在这方面的帮助

    '----------------Reading whole File ReadToEnd
    Dim sr As New StreamReader("C:\temp\100MB-File.txt")
    Dim path As String = "C:\temp\myFileNew1.txt"
    Dim oneLine As String
    oneLine = sr.ReadToEnd
    Using sw As StreamWriter = File.CreateText(path)
        sw.WriteLine(oneLine)
    End Using
    sr.Close()
    
    ''---------------Reading Line by Line
    Dim sr As New StreamReader("C:\temp\300MB-File.txt")
    Dim path As String = "C:\temp\myFileNew2.txt"
    Dim oneLine As String
    oneLine = sr.ReadLine
    
    Using sw As StreamWriter = File.CreateText(path)
        sw.WriteLine(oneLine)
    End Using
    
    Do Until sr.EndOfStream
        Console.WriteLine(oneLine)
        oneLine = sr.ReadLine()
    
        Using sw As StreamWriter = File.AppendText(path)
            sw.WriteLine(oneLine)
        End Using
    Loop
    sr.Close()
    

1 个答案:

答案 0 :(得分:3)

除了评论中提到的Console.WriteLine之外,您还要为正在编写的每一行打开和关闭输出文件。如果您只打开一次文件,它应该会快得多:

Dim sr As New StreamReader("C:\temp\300MB-File.txt")
Dim path As String = "C:\temp\myFileNew2.txt"
Dim oneLine As String
oneLine = sr.ReadLine

Using sw As StreamWriter = File.CreateText(path)
    sw.WriteLine(oneLine)
    Do Until sr.EndOfStream
        'Console.WriteLine(oneLine)
        oneLine = sr.ReadLine()
        sw.WriteLine(oneLine)
    Loop
End Using

sr.Close()

您还可以使用File.ReadLines简化代码:

Dim inPath As String = "C:\temp\300MB-File.txt"
Dim outPath As String = "C:\temp\myFileNew2.txt"

Using sw As StreamWriter = File.CreateText(outPath)
    For Each oneLine As String In File.ReadLines(inPath)
        ' modify line here
        sw.WriteLine(oneLine)
    Next
End Using