我有一个从文件中读取的函数,另一个函数用于写入文件。我尝试读写的文件是按顺序从1到3000的数字。我把文件读得很好并将其存储在一个名为numbers
的变量中。出于某种原因,当我写文件时,它会正确写入前2913行,但这是输出的结尾:
2908
2909
2910
2911
2912
2913
2
每次运行程序时,文件都以2914号的中间结束。该程序不会抛出异常。为什么会出现这种情况?
这是我的代码:
Sub Main() As Integer
Dim numbers As New List(Of String)
ReadFile(numbers, "C:\test.txt")
WriteFile(numbers, "C:\test2.txt")
End Function
Private Sub ReadFile(ByRef lines As List(Of String), _
ByVal filePath As String)
Dim sr As New System.IO.StreamReader(filePath)
Do While sr.Peek <> -1
lines.Add(sr.ReadLine)
Loop
End Sub
Private Sub WriteFile(ByVal lines As List(Of String), _
ByVal filePath As String)
Dim sw As New System.IO.StreamWriter(filePath, False)
For Each line In lines
sw.WriteLine(line)
Next
End Sub
答案 0 :(得分:3)
您还可以使用Using
块来避免这种情况:
Using sw As New System.IO.StreamWriter(filePath, False)
For Each line In lines
sw.WriteLine(line)
Next
End Using
如果你养成输入“使用”而不是“昏暗”的习惯,那么它会强制你考虑“结束使用”部分,它会自动关闭和处理流。
答案 1 :(得分:2)
我的问题是我没有关闭StreamWriter
。通过向StreamWriter.Close
方法添加WriteFile
,我就能解决问题。