我是新用户并且正在努力解决以下问题:
我需要阅读文件并回写一些修改,问题是:
我在“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()
答案 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