是的,我一直试图绕过这个但是,我想使用for循环来允许StreamWriter一次写一行;这就是我到目前为止所提出的:
Imports System.IO
Imports Microsoft.VisualBasic.FileIO
Module writeOneLineAtATime
Sub Main()
Dim fileWriter As StreamWriter
Dim lineOfCode As String
Dim fileName, filePath As String
'Get that file location, dog.
fileName = "sidneywashere.txt"
filePath = "Data\"
Debug.Print("File location: " + filePath + fileName)
fileWriter = My.Computer.FileSystem.OpenTextFileWriter(filePath + fileName, True)
Do
fileWriter.WriteLine("2butt")
fileWriter.Close()
Loop
Console.ReadLine()
End Sub
End Module
答案 0 :(得分:3)
有一种简单的方法可以做到这一点,如下所示:
Dim fullyQualifiedPath = Path.Combine(filePath, fileName)
Using sw As New StreamWriter(fullyQualifiedPath)
sw.WriteLine("Line1")
sw.WriteLine("Line2)
' etc.
End Using
将代码包装在Using
区块中意味着您完成后不需要Close
或Dispose
,因为这一切都得到了解决。
同样使用Path.Combine
比自己连接路径和文件更安全,但只要你连接字符串,就应该使用&
代替+
。