创建然后写入文本文件

creating then writing to a text file

我有一个按钮可以创建一个文本文件,还有一个文本框可以在我按下回车键时向文本文件写入内容。

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
    path = "C:\Testing.txt"
    File.Create(path)
End Sub

 If e.KeyCode = Keys.Enter Then
        System.IO.File.AppendAllText(path, TextBox1.Text & vbCrLf)
 End If

文件已正确创建,但当我想使用上面的代码写入文件时,出现错误。

The process cannot access the file 'C:\Testing.txt' because it is being used by another process.

根据 MSDNAppendAllText 将 "Opens a file, appends the specified string to the file, and then closes the file. If the file does not exist, this method creates a file, writes the specified string to the file, then closes the file."

更改此行:

File.Create(path)

为此:

File.Create(path).Dispose()

但是如前所述,您可以删除所有这些并简单地使用:

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
    path = "C:\Testing.txt"
    If e.KeyCode = Keys.Enter Then
        System.IO.File.AppendAllText(path, TextBox1.Text & vbCrLf)
    End If
End Sub