使用Visual Basic将多行写入文本文件

Jes*_*ord 2 vb.net streamwriter text-files

我正在尝试检查文件是否存在,如果是,它什么都不做.如果文件不存在则创建文本文件.然后我想写文件到那个文件.这个代码我哪里错了?我只是想在文本文件中写多行,而那部分不起作用.它正在创建文本文件......只是没有写入它.

Dim file As System.IO.FileStream
 Try
  ' Indicate whether the text file exists
  If My.Computer.FileSystem.FileExists("c:\directory\textfile.txt") Then
    Return
  End If

  ' Try to create the text file with all the info in it
  file = System.IO.File.Create("c:\directory\textfile.txt")

  Dim addInfo As New System.IO.StreamWriter("c:\directory\textfile.txt")

  addInfo.WriteLine("first line of text")
  addInfo.WriteLine("") ' blank line of text
  addInfo.WriteLine("3rd line of some text")
  addInfo.WriteLine("4th line of some text")
  addInfo.WriteLine("5th line of some text")
  addInfo.close()
 End Try
Run Code Online (Sandbox Code Playgroud)

Dar*_*rov 12

您似乎没有正确释放使用此文件分配的资源.

确保始终将IDisposable资源包装在Using语句中,以确保在使用完所有资源后立即正确释放所有资源:

' Indicate whether the text file exists
If System.IO.File.exists("c:\directory\textfile.txt") Then
    Return
End If

Using Dim addInfo = File.CreateText("c:\directory\textfile.txt")
    addInfo.WriteLine("first line of text")
    addInfo.WriteLine("") ' blank line of text
    addInfo.WriteLine("3rd line of some text")
    addInfo.WriteLine("4th line of some text")
    addInfo.WriteLine("5th line of some text")
End Using
Run Code Online (Sandbox Code Playgroud)

但在你的情况下使用该File.WriteAllLines方法似乎更合适:

' Indicate whether the text file exists
If System.IO.File.exists("c:\directory\textfile.txt") Then
    Return
End If

Dim data As String() = {"first line of text", "", "3rd line of some text", "4th line of some text", "5th line of some text"}
File.WriteAllLines("c:\directory\textfile.txt", data)
Run Code Online (Sandbox Code Playgroud)