如何在vb.net中保存用户输入

时间:2018-05-31 22:45:48

标签: vb.net visual-studio

我正在编写我的第一个vb.net应用程序。它基本上将文件从用户输入源位置复制到另一个用户输入目标位置。我想添加一个按钮,在源位置和目标位置保存用户输入。

Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

    TextBox1.Text = ""
    If FolderBrowserDialog1.ShowDialog() = DialogResult.OK Then
        TextBox1.Text = FolderBrowserDialog1.SelectedPath
    Else TextBox1.Text = ""

    End If


End Sub

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click

    TextBox2.Text = ""
    If FolderBrowserDialog1.ShowDialog() = DialogResult.OK Then
        TextBox2.Text = FolderBrowserDialog1.SelectedPath
    Else TextBox2.Text = ""

    End If


End Sub

Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click


    Me.Refresh()
    Label1.Text = "Working... Please do not close this window. Even if says not responding  "

    Dim location As String
    Dim locationsave As String

    location = TextBox1.Text
    locationsave = TextBox2.Text
    Try

        Me.Refresh()
        My.Computer.FileSystem.CopyDirectory(location, locationsave, True)
        Label1.Text = "Completed! Backed up to: " & locationsave

    Catch ex As Exception

        MessageBox.Show("Either your source location or destination location does not exist! Please check them and try again.", "Oops!")

    End Try

End Sub
End Class

1 个答案:

答案 0 :(得分:1)

假设我们正在处理简单的文本文件。此代码适用于您,但可以进行改进。

        //Path of input file, i.e. "test.txt"
        string inputLocation = "Input file location";
        //destination file location
        string destinationLocation = "Output file location";
        //value user wants to add to file.
        string userInput = "some user input";


        //Create a stream reader, this will read the input file
        StreamReader sr = new StreamReader(inputLocation);
        //Save the file's contents to a variable
        string fileContents = sr.ReadToEnd();
        //close the stream reader, otherwise you wont be able to write to the file
        sr.Close();

        //Open a stream writer to append the user input to the original file
        StreamWriter sw = new StreamWriter(inputLocation,true);
        //Append the user inout to the file
        sw.WriteLine(userInput);
        //close the file
        sw.Close();

        //Open a stream writer to write the new file
        sw = new StreamWriter(destinationLocation,false);
        //add the original file contents to the new file
        sw.WriteLine(fileContents);
        //add the user input to the new file
        sw.WriteLine(userInput);
        //close the new file
        sw.Close();

更多阅读: