I'm trying to save my textbox1 content into a text file to my computer.
What I want to do is to create a save directory and when it's set up, I will save the content of textbox1 to that txt file.
Not just once, I want to append the content of the TextBox to the same file after.
Button2: Trying to browse and create a txt file.
Button4 (1st click): This button will save the content of textbox1 to the txt file created.
Button4 (2nd click)": this will add the current content of textbox1 to the same txt file.
But I want to be able to change the directory whenever I want.
I also want to choose path outside the code or outside the textbox.
Meaning, I want a button that will let me choose a folder where I want to create a text file.
The 2nd button will let me save the textbox1 content to the created text file.
Here's some of my code but I don't know if I'm doing it correctly because it's now doing what I want. Please help.
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim isave As New SaveFileDialog
isave.Filter = "txt files (*.txt) |*.txt"
isave.FilterIndex = 2
isave.RestoreDirectory = False
If isave.ShowDialog() = DialogResult.OK Then
IO.File.WriteAllText(isave.FileName, TextBox1.Text)
End If
End Sub
Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click
Dim theText As String
theText = TextBox1.Text
IO.File.AppendAllText("isave", Environment.NewLine & theText)
End Sub
A possible way to proceed:
lastSaveFileNamehere) to store the path of the last file saved.lastSaveFileNamelastSaveFileNameis set to an empty string, so you cannot append new text to this file.If this is not the behavior you're expecting (i.e., you want to preserve and update a file created in a previous session), then remove
sfd.OverwritePrompt = Trueand useFile.AppendAllText()instead ofFile.WriteAllText()lastSaveFileNamereferenceI've renamed the Buttons to
SaveFileandUpdateFileand the TextBox toTextContent: it's always better to assign meaningful names to your ControlsThe SaveFileDialog object must be declared with an
Usingstatement, since you need to dispose of it when it's closed (a window shown withShowDialog()cannot dispose of itself. Declaring a disposable object with anUsingstatement, ensures that the object is disposed even if an exception is raised in the meanwhile; most of the times)