在 VB.NET 中创建文本并将其附加到 txt 文件 [英] Creating and appending text to txt file in VB.NET
本文介绍了在 VB.NET 中创建文本并将其附加到 txt 文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
使用 VB.NET,我尝试创建一个文本文件(如果它不存在)或将文本附加到它(如果存在).
Using VB.NET, I am trying to create a text file if it doesn't exist or append text to it if exists.
出于某种原因,虽然它正在创建文本文件,但我收到一条错误消息,说进程无法访问文件.
For some reason, though it is creating the text file I am getting an error saying process cannot access file.
当我运行程序时,它正在写入文本,但如何让它在新行上写入?
And when I run the program it is writing text, but how can I make it write on a new line?
Dim strFile As String = "C:\ErrorLog_" & DateTime.Today.ToString("dd-MMM-yyyy") & ".txt"
Dim sw As StreamWriter
Dim fs As FileStream = Nothing
If (Not File.Exists(strFile)) Then
Try
fs = File.Create(strFile)
sw = File.AppendText(strFile)
sw.WriteLine("Start Error Log for today")
Catch ex As Exception
MsgBox("Error Creating Log File")
End Try
Else
sw = File.AppendText(strFile)
sw.WriteLine("Error Message in Occured at-- " & DateTime.Now)
sw.Close()
End If
推荐答案
试试这个:
Dim strFile As String = "yourfile.txt"
Dim fileExists As Boolean = File.Exists(strFile)
Using sw As New StreamWriter(File.Open(strFile, FileMode.OpenOrCreate))
sw.WriteLine( _
IIf(fileExists, _
"Error Message in Occured at-- " & DateTime.Now, _
"Start Error Log for today"))
End Using
这篇关于在 VB.NET 中创建文本并将其附加到 txt 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文