使用 Visual Basic 将多行写入文本文件 [英] Write mutiple lines to a text file using Visual Basic
问题描述
我正在尝试检查文件是否存在,如果存在则什么也不做.如果文件不存在,则创建文本文件.然后我想将文本写入该文件.这段代码我哪里出错了?我只是想将多行写入文本文件,但该部分不起作用.它正在创建文本文件......只是不写入它.
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
推荐答案
您似乎没有正确释放您使用此文件分配的资源.
You don't seem to be properly releasing the resources you allocated with this file.
确保始终将 IDisposable
资源包装在 Using 语句中,以确保所有资源在使用完后立即正确释放:
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
但在您的情况下使用 File.WriteAllLines
方法似乎更合适:
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)
这篇关于使用 Visual Basic 将多行写入文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!