[英]VB.NET: Using StreamWriter to write one line at a time
Yeah, I've been trying to wrap my head around this but, I want to use a for loop to allow StreamWriter to write one line at a time;是的,我一直在试图解决这个问题,但是,我想使用 for 循环来允许 StreamWriter 一次写一行; this is what i've come up with so far:
这是我到目前为止想出的:
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 = "someonewashere.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
There is an easy way to do this which is as follows:有一种简单的方法可以做到这一点,如下所示:
Dim fullyQualifiedPath = Path.Combine(filePath, fileName)
Using sw As New StreamWriter(fullyQualifiedPath)
sw.WriteLine("Line1")
sw.WriteLine("Line2)
' etc.
End Using
Wrapping the code in a Using
block means that you don't have to Close
or Dispose
of it when you are done as that is all taken care of.将代码包装在
Using
块中意味着您在完成后不必Close
或Dispose
它,因为这一切都已完成。
Also using Path.Combine
is safer than concatenating the path and file yourself, but anytime you are concatenating strings you should use &
instead of +
.同样使用
Path.Combine
比自己连接路径和文件更安全,但是任何时候连接字符串都应该使用&
而不是+
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.