2

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
Jimi
  • 29,621
  • 8
  • 43
  • 61
Newbie TJ
  • 35
  • 5
  • 1
    You have to store the most recent `SaveFileDialog.FileName` and use it to append text to that file later on. You should also decide what to do in case the file doesn't exist at that point, since `File.AppendAllText()` creates a new one when the file specified is not there -- You should (really) declare the SaveFileDialog object with an `Using` statement – Jimi Dec 29 '22 at 12:14
  • Oh, yes I have to prepare also if ever the txtfile is not on the directory. But can you tell me the code for that? Can you correct my codes please. – Newbie TJ Dec 29 '22 at 14:06
  • @NewbieTJ Side note: You can also go into Visual Studio's own NuGet package manager and download the _Microsoft.WindowsAPICodePack-Shell package_ . Then you have a modern SaveFileDialog. – Daniel Jan 04 '23 at 12:16
  • 1
    Using SFD As New Microsoft.WindowsAPICodePack.Dialogs.CommonSaveFileDialog() SFD.Title = "Your title" SFD.Filters.Add(New Microsoft.WindowsAPICodePack.Dialogs.CommonFileDialogFilter("", ".txt")) If System.IO.Directory.Exists("your Path") Then SFD.InitialDirectory = "your Path" Else SFD.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) End If – Daniel Jan 04 '23 at 12:17
  • 1
    If SFD.ShowDialog() = Microsoft.WindowsAPICodePack.Dialogs.CommonFileDialogResult.Ok Then '... Else Return End If End Using – Daniel Jan 04 '23 at 12:18
  • 1
    You can do the same for an OpenFileDialog. If you want this to be Multiselect then write OFD.Multiselect = True – Daniel Jan 04 '23 at 12:18

1 Answers1

2

A possible way to proceed:

  • Use a Field (lastSaveFileName here) to store the path of the last file saved.
  • Use a SaveFileDialog to get the file path, store the result in lastSaveFileName
    • The SaveFileDialog asks for confirmation if the file already exists. The user may choose to overwrite it or not
    • If the user chooses not to overwrite the existing file (hence cancels the operation), the lastSaveFileName is 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 = True and use File.AppendAllText() instead of File.WriteAllText()
  • To update the selected file, adding more text, use the previously stored lastSaveFileName reference
    • If the file doesn't exist - at this time - or it has never been specified, prompt the user to create the file first. You could also store the file path in the Project's Settings

I've renamed the Buttons to SaveFile and UpdateFile and the TextBox to TextContent: it's always better to assign meaningful names to your Controls

The SaveFileDialog object must be declared with an Using statement, since you need to dispose of it when it's closed (a window shown with ShowDialog() cannot dispose of itself. Declaring a disposable object with an Using statement, ensures that the object is disposed even if an exception is raised in the meanwhile; most of the times)


Imports System.IO

Private lastSaveFileName As String = String.Empty

Private Sub SaveFile_Click(sender As Object, e As EventArgs) Handles SaveFile.Click
    lastSaveFileName = GetSaveFileName(lastSaveFileName)
    If Not String.IsNullOrEmpty(lastSaveFileName) Then
        File.WriteAllText(lastSaveFileName, TextContent.Text)
    End If
End Sub

Private Sub UpdateFile_Click(sender As Object, e As EventArgs) Handles UpdateFile.Click
    If Not String.IsNullOrEmpty(lastSaveFileName) AndAlso File.Exists(lastSaveFileName) Then
        File.AppendAllText(lastSaveFileName, Environment.NewLine & TextContent.Text)
    Else
        MessageBox.Show(
            Me, "The file has not been created yet [other instructions]",
            "Save file missing", MessageBoxButtons.OK, MessageBoxIcon.Information
        )
    End If
End Sub

Private Function GetSaveFileName(suggestedName As String) As String
    Using sfd As New SaveFileDialog()
        sfd.Filter = "Text Files (*.txt) |*.txt"
        sfd.FileName = suggestedName
        sfd.OverwritePrompt = True
        If sfd.ShowDialog() = DialogResult.OK Then
            Return sfd.FileName
        End If
        Return String.Empty
    End Using
End Function
Jimi
  • 29,621
  • 8
  • 43
  • 61
  • Thank you. This code works and really is a big help to my study program. Thank you for the explanation I'm learning. There is only one thing left. Using your code, I was able to create a txtfile, I was able to update the content of the same txtfile but it's only I don't exit the app. I stop the program and run again, try to continue the update but it requires me to create new one since overwriting will delete my previous saved contents. How can I continue the update on the same txt file even after exiting the app? I want to continue when I get back. Please help. – Newbie TJ Dec 29 '22 at 15:54
  • 1
    It's described in the ***If this is not the behavior you're expecting*** section and, eventually, see the note about storing the selected path the Project' Settings (`My.Settings`), in case you need to preserve the last previously saved file path between runs – Jimi Dec 29 '22 at 16:00
  • Ohhh. Sorry I think I need rest to fully understand and learn your shared knowledge. Thank you again. You really helped me. – Newbie TJ Dec 29 '22 at 16:44
  • I tried it but not sure if I did it correctly. – Newbie TJ Jan 01 '23 at 04:27
  • I tried it but not sure if I did it correctly. Is the `File.AppendAllText()` gonna replace the `sfd.OverwritePrompt = True` in the `Private Function` or in `Private Sub SaveFile`? I tried to replace the `File.WriteAllText` on SaveFile but it shows dialog if I want to replace the file on my last session. – Newbie TJ Jan 01 '23 at 04:46
  • I tried to put the code this way `Using sfd As New SaveFileDialog() sfd.Filter = "Text Files (*.txt) |*.txt" sfd.FileName = suggestedName 'sfd.OverwritePrompt = True File.AppendAllText(lastSaveFileName, TextContent.Text) If sfd.ShowDialog() = DialogResult.OK Then Return sfd.FileName End If Return String.Empty End Using ` But it shows error: ArgumentExpectation was unhandled Empty path name is not legal. Can you show me how to do it correctly? Thank you. – Newbie TJ Jan 01 '23 at 04:46
  • 1
    Nope, `File.AppendAllText()` replaces `File.WriteAllText()` in `SaveFile_Click()`. In the `GetSaveFileName()` method, just set `sfd.OverwritePrompt = False` – Jimi Jan 02 '23 at 04:17
  • Oh great! It's working. This is what I really want to happen. Thank you very much. You really are a big help. Now I can experiment again using this. Another learning hehe. – Newbie TJ Jan 02 '23 at 05:40