如何使用 vb.net 将文本框值写入 .txt 文件

问题描述:

我有一个带有两个文本框的简单表单,我希望 Textbox1 写入名为 C:\VALUE1.txtTextbox2 的文件将其值写入名为 C:\VALUE2.txt

I have a simple form with two textboxes, I want Textbox1 to write to a file named C:\VALUE1.txt and Textbox2 to write its value to a file named C:\VALUE2.txt

必须覆盖文本文件中已有的任何文本.

Any text that is already in the text file MUST be over written.

这两种方法都值得熟悉:

It's worth being familiar with both methods:

1) 在 VB.Net 中,您有快速简便的 My.Computer.FileSystem.WriteAllText 选项:

1) In VB.Net you have the quick and easy My.Computer.FileSystem.WriteAllText option:

My.Computer.FileSystem.WriteAllText("c:\value1.txt", TextBox1.Text, False)

2) 否则,您可以走长"路并使用 StreamWriter 对象.如下创建一个 - 在构造函数中设置 false 告诉它你不想追加:

2) Or else you can go the "long" way round and use the StreamWriter object. Create one as follows - set false in the constructor tells it you don't want to append:

Dim objWriter As New System.IO.StreamWriter("c:\value1.txt", False)

然后将文本写入文件,如下所示:

then write text to the file as follows:

objWriter.WriteLine(Textbox1.Text)
objWriter.Close()