Write mutiple lines to a text file using Visual Basic

自作多情 提交于 2019-12-21 06:02:03

问题


I'm trying to check to see if a file exists, if so it does nothing. If the file does not exist is creates the text file. Then I want to write text to that file. Where am I going wrong with this code? I'm just trying to write multiple lines to the text file and that part is not working. It is creating the text file... just not writing to it.

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

回答1:


You don't seem to be properly releasing the resources you allocated with this file.

Make sure that you always wrap IDisposable resources in Using statements to ensure that all resources are properly released as soon as you have finished working with them:

' 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

but in your case using the File.WriteAllLines method seems more appropriate:

' 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)



回答2:


It all works great! - This is not the best way to create and write to a file - I'd rather create the text I want to write and then just write it to a new file, but given your code, all that is missing is having to close the created file before writing to it. Just change this line:

file = System.IO.File.Create("c:\directory\textfile.txt")

to:

file = System.IO.File.Create("c:\directory\textfile.txt")
file.close

All the rest will work.




回答3:


 file = System.IO.File.Create("path")

Close the file once created then try to write to it.

 file.Close()
     Dim addInfo As New System.IO.StreamWriter("path")


来源:https://stackoverflow.com/questions/14903938/write-mutiple-lines-to-a-text-file-using-visual-basic

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!