vb.net Visual Basic:打开、保存和另存为:从文本框到文本文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25859756/
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
Visual Basic: Open, Save, and Save as: Into text files from textboxes?
提问by Greg
Ok I'm trying to get 3 buttons working, save, save as and open. Basically when a user opens the a file (optional) and they edit it (in a textbox) they can save it automatically back to that same text document or save it as a new one and continue to edit it from that new one they created. I am using 1 open file dialog and 1 save dialog, im really confused can someone please write the code for each button. please
好的,我正在尝试让 3 个按钮工作,保存,另存为和打开。基本上,当用户打开文件(可选)并对其进行编辑(在文本框中)时,他们可以将其自动保存回相同的文本文档或将其另存为新文档并继续从他们创建的新文档中进行编辑。我正在使用 1 个打开文件对话框和 1 个保存对话框,我真的很困惑有人可以为每个按钮编写代码。请
回答by Mark Hall
Try something like this, it is working. I created a common save routine that will check if the workingFileName is Null and open the Save Dialog box to prompt for a FileName so that it will handle both cases.
尝试这样的事情,它正在工作。我创建了一个通用的保存例程,它将检查workingFileName 是否为空并打开保存对话框以提示输入文件名,以便它处理这两种情况。
Imports System.IO
Public Class Form1
Dim workingFileName As String
Private Sub Load_Click(sender As Object, e As EventArgs) Handles Open.Click
OfOpen.ShowDialog()
workingFileName = OfOpen.FileName
If String.IsNullOrEmpty(workingFileName) Then
MsgBox("FileName error please correct")
Exit Sub
End If
Dim sr As StreamReader = File.OpenText(workingFileName)
tbText.Text = sr.ReadToEnd
sr.Close()
End Sub
Private Sub Save_Click(sender As Object, e As EventArgs) Handles Save.Click
Save_Routine(workingFileName)
End Sub
Private Sub Save_Routine(fileName As String)
If String.IsNullOrEmpty(fileName) Then
Dim sd As New SaveFileDialog()
sd.ShowDialog()
workingFileName = sd.FileName
If String.IsNullOrEmpty(workingFileName) Then Exit Sub
End If
Dim sw As StreamWriter = New StreamWriter(workingFileName)
sw.Write(tbText.Text)
sw.Close()
End Sub
Private Sub SaveAs_Click(sender As Object, e As EventArgs) Handles SaveAs.Click
Save_Routine("")
End Sub
End Class
回答by Yehia Elhawary
Add Save file dialog tool to your form and try:
将保存文件对话框工具添加到您的表单并尝试:
Private Sub SaveAsButton_Click(sender As Object, e As EventArgs) Handles SaveAsButton.Click
If SaveFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
Dim sWriter As New IO.StreamWriter(SaveFileDialog1.FileName & ".txt", False)
sWriter.Write(tbText.Text)
sWriter.Close()
End If
End Sub
stream writer will overwrite the file.
流编写器将覆盖文件。

