如何使用 vb.net 将文本框值写入 .txt 文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5002529/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to write textbox values to .txt file with vb.net
提问by jason
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
我有两个文本框一个简单的表格,我想Textbox1
写信给一个指定的文件C:\VALUE1.txt
和Textbox2
它的值写入到一个指定的文件C:\VALUE2.txt
Any text that is already in the text file MUST be over written.
任何已经存在于文本文件中的文本都必须被覆盖。
回答by hawbsl
It's worth being familiar with both methods:
这两种方法都值得熟悉:
1) In VB.Net you have the quick and easy My.Computer.FileSystem.WriteAllText option:
1) 在 VB.Net 中,您有快速简便的 My.Computer.FileSystem.WriteAllText 选项:
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 falsein the constructor tells it you don't want to append:
2)否则,您可以走“长”路并使用 StreamWriter 对象。创建一个如下 -在构造函数中设置false告诉它你不想追加:
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()
回答by Gabriel Spiteri
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
回答by sasfrog
Have a look at the System.IO
and System.Text
namespaces, in particular the StreamWriter
object.
查看System.IO
和System.Text
命名空间,尤其是StreamWriter
对象。