读取/写入大文件 VB.NET [英] Reading/Writing Large Files VB.NET
问题描述
我是新用户,正在为以下问题苦苦挣扎:
I am a new user and struggling with the below:
我需要读取文件并写回一些修改,问题是:
I would need to read the file and write back with some modifications, the issue is:
- ReadToEnd"适用于较小的文件 [约 100MB],并且一切正常,我喜欢做的事情.但是对于更大的文件 [300 MB +],它会爆炸.
- 然后我尝试了ReadLine"(逐行阅读)它适用于较小或较大的文件,但保存起来需要很长时间.
我在ReadToEnd"和ReadLine"下面包含了两个代码为了进行测试,您需要在 c:\temp\ 区域中创建100MB-File.txt"和300MB-File.txt"文件.
I have included both of the codes below "ReadToEnd" and "ReadLine" For testing you would need to create "100MB-File.txt" and "300MB-File.txt" files in c:\temp\ area.
非常感谢您在这方面的帮助
I would really appreciate your help in this regard
'----------------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()
推荐答案
除了注释中提到的 Console.WriteLine
之外,您正在为正在编写的每一行打开和关闭输出文件.如果只打开一次文件,应该会快很多:
In addition to the Console.WriteLine
mentioned in the comments, you are opening and closing the output file for each line you are writing. If you just open the file once, it should be much faster:
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
来简化代码:
You could also simplify the code using 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
这篇关于读取/写入大文件 VB.NET的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!