Visual Basic:打开,保存和另存为:从文本框中转换为文本文件?

时间:2014-09-16 02:22:38

标签: vb.net visual-studio-2010

好的我正试图让3个按钮工作,保存,保存和打开。基本上,当用户打开文件(可选)并对其进行编辑(在文本框中)时,他们可以将其自动保存回同一文本文档或将其另存为新文档并继续从他们创建的新文档进行编辑。我正在使用1个打开文件对话框和1个保存对话框,我真的很困惑可以有人请为每个按钮编写代码。请

2 个答案:

答案 0 :(得分:1)

尝试这样的事情,它正在发挥作用。我创建了一个公共保存例程,它将检查workingFileName是否为Null并打开Save对话框以提示输入FileName,以便它可以处理这两种情况。

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

答案 1 :(得分:1)

将保存文件对话框工具添加到表单并尝试:

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

流编写器将覆盖该文件。