我有以下代码将文本从文本框保存到目录中,当文件保存的文本框清除所有文本但代码清除文本框并且当我在目录中打开文件为空时,我想要的问题是如何检查文件是否已保存并清除(但文件随机保存)
If Not (System.IO.Directory.Exists("C:\Users\" + Environment.UserName.ToString + "\AppData\SystemInfo\TextLogs")) Then
My.Computer.FileSystem.CreateDirectory("C:\Users\" + Environment.UserName.ToString + "\AppData\SystemInfo\TextLogs")
End If
If (System.IO.Directory.Exists("C:\Users\" + Environment.UserName.ToString + "\AppData\SystemInfo\TextLogs")) Then
Dim count As Integer = -1
Dim files As String = TextBox1.Text
Dim writerz As New IO.StreamWriter("C:\Users\" + Environment.UserName.ToString + "\AppData\SystemInfo\TextLogs\" & DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".txt")
writerz.WriteLine(files)
textbox1.clear()
End If
答案 0 :(得分:1)
您需要关闭并处置StreamWriter,因为它的内部数据缓冲区不会在每次调用WriteLine时都写入磁盘
Dim folder = System.IO.Path.Combine("C:\Users", Environment.UserName,"AppData\SystemInfo\TextLogs"
System.IO.Directory.CreateDirectory(folder)
Dim file = System.IO.Path.Combine(folder,DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".txt")
Using writerz As New IO.StreamWriter(file)
writerz.WriteLine(files)
End Using
在这里,Using
语句可确保在代码到达End Using
语句时正确关闭并处置文件
旁注: