How to write textbox values to .txt file with vb.n

2019-01-09 05:04发布

问题:

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.

回答1:

It's worth being familiar with both methods:

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) 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()


回答2:

Dim FILE_NAME As String = "C:\VALUE2.txt"
If System.IO.File.Exists(FILE_NAME) = True Then
  Dim objWriter As New System.IO.StreamWriter(FILE_NAME)
  objWriter.Write(TextBox2.Text)
  objWriter.Close()
  MsgBox("Text written to file")
Else
  MsgBox("File Does Not Exist")
End If


回答3:

Have a look at the System.IO and System.Text namespaces, in particular the StreamWriter object.