VB.NET:使用StreamWriter一次写一行

时间:2015-10-21 09:35:59

标签: .net vb.net loops filesystems streamwriter

是的,我一直试图绕过这个但是,我想使用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

1 个答案:

答案 0 :(得分:3)

有一种简单的方法可以做到这一点,如下所示:

Dim fullyQualifiedPath = Path.Combine(filePath, fileName)

Using sw As New StreamWriter(fullyQualifiedPath)
    sw.WriteLine("Line1")
    sw.WriteLine("Line2)
    ' etc.
End Using

将代码包装在Using区块中意味着您完成后不需要CloseDispose,因为这一切都得到了解决。

同样使用Path.Combine比自己连接路径和文件更安全,但只要你连接字符串,就应该使用&代替+