Results 1 to 23 of 23

Thread: How to create txt file and append text to existing txt file?

  1. #1

    Thread Starter
    Junior Member
    Join Date
    Dec 2022
    Posts
    19

    How to create txt file and append text to existing txt file?

    Using VB net,
    I'm trying to save my textbox1 content into a txtfile to my computer.
    What I want to do is to create a save directory and when it's set up, I will save the textbox1 content to that txt file. Not just once but I want to save the 2nd content of textbox1 to the same txt file like append text.


    Button 2: Trying to browse and create a txt file.
    Button 4(1st click): This button will save the content of textbox1 to the txt file created.
    Button 4(2nd click)" This will add another 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 txt file.
    The 2nd button will let me save the textbox1 content to the created txt 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.

    Code:
    `
    ```
    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
    ```
    `

  2. #2
    PowerPoster Poppa Mintin's Avatar
    Join Date
    Mar 2009
    Location
    Bottesford, North Lincolnshire, England.
    Posts
    2,429

    Re: How to create txt file and append text to existing txt file?

    Hi Maxtertj,

    I'd use something like this...
    Code:
     If My.Computer.FileSystem.FileExists(filePath) Then
                FileOpen(1, filePath, OpenMode.Append)
    Poppa
    Along with the sunshine there has to be a little rain sometime.

  3. #3
    eXtreme Programmer .paul.'s Avatar
    Join Date
    May 2007
    Location
    Chelmsford UK
    Posts
    25,479

    Re: How to create txt file and append text to existing txt file?

    Quote Originally Posted by Poppa Mintin View Post
    Hi Maxtertj,

    I'd use something like this...
    Code:
     If My.Computer.FileSystem.FileExists(filePath) Then
                FileOpen(1, filePath, OpenMode.Append)
    Poppa
    Poppa Minton. That’s not a good suggestion. FileOpen is legacy code, that was superseded 20 years ago. There is absolutely no need to use legacy code…

  4. #4

    Thread Starter
    Junior Member
    Join Date
    Dec 2022
    Posts
    19

    Re: How to create txt file and append text to existing txt file?

    What could be the right code I can use?

  5. #5
    eXtreme Programmer .paul.'s Avatar
    Join Date
    May 2007
    Location
    Chelmsford UK
    Posts
    25,479

    Re: How to create txt file and append text to existing txt file?

    If you want to check a file exists, you can use io.file.exists, but don’t use that fileopen code that Poppa Mintin posted.
    There are many ways to skin a cat in vb.net. I’ll find you a link to some examples…

  6. #6
    eXtreme Programmer .paul.'s Avatar
    Join Date
    May 2007
    Location
    Chelmsford UK
    Posts
    25,479

    Re: How to create txt file and append text to existing txt file?


  7. #7
    PowerPoster PlausiblyDamp's Avatar
    Join Date
    Dec 2016
    Location
    Pontypool, Wales
    Posts
    2,473

    Re: How to create txt file and append text to existing txt file?

    Have a look at https://learn.microsoft.com/en-us/dotnet/api/system.io.streamwriter.-ctor?view=net-7.0#system-io-streamwriter-ctor(system-string-system-boolean-system-text-encoding) it is probably a good starting point.
    Last edited by PlausiblyDamp; Dec 29th, 2022 at 07:53 AM.

  8. #8
    eXtreme Programmer .paul.'s Avatar
    Join Date
    May 2007
    Location
    Chelmsford UK
    Posts
    25,479

    Re: How to create txt file and append text to existing txt file?


  9. #9

    Thread Starter
    Junior Member
    Join Date
    Dec 2022
    Posts
    19

    Re: How to create txt file and append text to existing txt file?

    Thank you guys for sharing and helping.
    But I will be a big help if you show me codes that I can use

  10. #10
    PowerPoster ChrisE's Avatar
    Join Date
    Jun 2017
    Location
    Frankfurt
    Posts
    3,048

    Re: How to create txt file and append text to existing txt file?

    Quote Originally Posted by maxtertj View Post
    Thank you guys for sharing and helping.
    But I will be a big help if you show me codes that I can use
    did you look at the Links in Post #6 and #8 ?
    they will get you started
    to hunt a species to extinction is not logical !
    since 2010 the number of Tigers are rising again in 2016 - 3900 were counted. with Baby Callas it's 3901, my wife and I had 2-3 months the privilege of raising a Baby Tiger.

  11. #11
    Lively Member
    Join Date
    Dec 2021
    Posts
    100

    Re: How to create txt file and append text to existing txt file?

    Code:
      With TXT_multilinetxtbox
                .AppendText(txtsource)
                
    
            End With
            TXT_multilinetxtbox.Text += vbCrLf
    I'm using this code to make a multiline entries in my txt_box

  12. #12
    PowerPoster Poppa Mintin's Avatar
    Join Date
    Mar 2009
    Location
    Bottesford, North Lincolnshire, England.
    Posts
    2,429

    Re: How to create txt file and append text to existing txt file?

    Quote Originally Posted by .paul. View Post
    Poppa Mintin. That’s not a good suggestion. FileOpen is legacy code, that was superseded 20 years ago. There is absolutely no need to use legacy code…
    I've been coding in BASIC since 1978 and and Visual BASIC since 1990, so as I said. I'd use the code I posted. (Because it answers the question and it still works) I'd be surprised if it was as long ago as 20 years that it was superseded, who knows? When you get to my age... who cares!


    Poppa
    Along with the sunshine there has to be a little rain sometime.

  13. #13
    eXtreme Programmer .paul.'s Avatar
    Join Date
    May 2007
    Location
    Chelmsford UK
    Posts
    25,479

    Re: How to create txt file and append text to existing txt file?

    Quote Originally Posted by Poppa Mintin View Post
    I've been coding in BASIC since 1978 and and Visual BASIC since 1990, so as I said. I'd use the code I posted. (Because it answers the question and it still works) I'd be surprised if it was as long ago as 20 years that it was superseded, who knows? When you get to my age... who cares!


    Poppa
    I’ve been programming in VB since the early 90s, starting with VB3. Sure there was code in those days that was fairly efficient, but it was superseded after VB6. If you want to use out of date methods, that’s fine. But it’s not fine to recommend those out of date methods to beginners who are here to learn how to program properly in a modern language…

  14. #14

    Thread Starter
    Junior Member
    Join Date
    Dec 2022
    Posts
    19

    Re: How to create txt file and append text to existing txt file?

    Quote Originally Posted by ChrisE View Post
    did you look at the Links in Post #6 and #8 ?
    they will get you started
    Yes. I checked those links but I see codes for C#.

    I don't know that language yet.
    The constructors, fields, properties, methods are there but I'm not yet pro to build something from that
    So, I'm wondering for working code that is ready to use. Then explanation for what's happening on the code will be helpful and appreciated.

  15. #15
    eXtreme Programmer .paul.'s Avatar
    Join Date
    May 2007
    Location
    Chelmsford UK
    Posts
    25,479

    Re: How to create txt file and append text to existing txt file?

    Quote Originally Posted by maxtertj View Post
    Yes. I checked those links but I see codes for C#.
    At the top of both of those pages, there’s a toggle control which can be used to change the page code to VB or to C#

  16. #16
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    110,344

    Re: How to create txt file and append text to existing txt file?

    Quote Originally Posted by Poppa Mintin View Post
    I'd be surprised if it was as long ago as 20 years that it was superseded, who knows?
    Many people know. The first version of VB.NET was released in 2002 so, as of today, it's 21 years.

  17. #17

    Thread Starter
    Junior Member
    Join Date
    Dec 2022
    Posts
    19

    Re: How to create txt file and append text to existing txt file?

    Quote Originally Posted by .paul. View Post
    At the top of both of those pages, there’s a toggle control which can be used to change the page code to VB or to C#
    Thank you, I was able to change it on the VB version code.
    I don't know how to try the code there.

    I copy and paste it to my form.

    I run the form without anything there, hehe I think I did it wrong because it's not working.

    Can you help me?

  18. #18
    PowerPoster PlausiblyDamp's Avatar
    Join Date
    Dec 2016
    Location
    Pontypool, Wales
    Posts
    2,473

    Re: How to create txt file and append text to existing txt file?

    Quote Originally Posted by maxtertj View Post
    Thank you, I was able to change it on the VB version code.
    I don't know how to try the code there.

    I copy and paste it to my form.

    I run the form without anything there, hehe I think I did it wrong because it's not working.

    Can you help me?
    Show us your code then, we can't see it if you don't show it.

    Explain what is going wrong, we aren't psychic. "It's not working" doesn't give us the slightest hint of what is going wrong... Is it not appending? Is it overwriting the file? Is it not opening the file? Is it deleting random files from your computer? Please give us enough information to work with if you want help!

  19. #19

    Thread Starter
    Junior Member
    Join Date
    Dec 2022
    Posts
    19

    Re: How to create txt file and append text to existing txt file?

    Sorry for that.

    This is what I'm saying.
    I copied this code and paste it on my form

    Code:
    Imports System.IO
    Public Class _29FileClass
    
    
    
    
        Public Class Test
            Public Shared Sub Main()
                Dim path As String = "C:\Users\AMIZOZ\Downloads\Study\Study\bin\Debug\louietot.txt"
                If File.Exists(path) = False Then
                    ' Create a file to write to.
                    Using sw As StreamWriter = File.CreateText(path)
                        sw.WriteLine("Hello")
                        sw.WriteLine("And")
                        sw.WriteLine("Welcome")
                    End Using
                End If
    
                ' Open the file to read from.
                Using sr As StreamReader = File.OpenText(path)
                    Do While sr.Peek() >= 0
                        Console.WriteLine(sr.ReadLine())
                    Loop
                End Using
            End Sub
        End Class
    End Class
    I don't know where to put that code so I just paste it directly.
    The button1 doesn't have any code.

    So I'm confuse how the code provided from your suggestion will work.

  20. #20
    Frenzied Member
    Join Date
    Apr 2016
    Posts
    1,415

    Re: How to create txt file and append text to existing txt file?

    Hi Max,

    Your final code in #19 is not really going to do everything you said in the begin...

    But I want to be able to change the directory whenever I want.
    that path looks hard coded.. You can use a folderBrowserDialog... Also what happened to the buttons click as per your original post?

    'You did not say of the txt file will always be there so maybe. For your button2 browse and create the text file. This is how I would do it:

    Code:
    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
    
        Dim folderBrowserDialog1 As New FolderBrowserDialog()
    
        If folderBrowserDialog1.ShowDialog() = DialogResult.OK Then
            Dim folderPath As String = folderBrowserDialog1.SelectedPath
            Dim fileName As String = Path.Combine(folderPath, "louietot.txt")
    
            ' then if that file does not exist then create it
            If Not File.Exists(fileName) Then
                File.Create(fileName).Dispose()
            End If
        End If
    End Sub

    You want to click on your button4 two times:

    first click:

    Code:
    Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
    
        ' you must declare a FolderBrowserDialog object
        Dim folderBrowserDialog1 As New FolderBrowserDialog()
    
        ' you selects a folder and clicks OK
        If folderBrowserDialog1.ShowDialog() = DialogResult.OK Then
    
            ' get the selected folder path
            Dim folderPath As String = folderBrowserDialog1.SelectedPath
    
            ' Create the file path by combining the folder path and the file name
            Dim fileName As String = Path.Combine(folderPath, "louietot.txt")
    
            ' Write the contents of TextBox1 to the file
            System.IO.File.WriteAllText(fileName, TextBox1.Text)
    
        End If
    End Sub

    second click:

    Code:
    Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
        ' declare a FolderBrowserDialog object
        Dim folderBrowserDialog1 As New FolderBrowserDialog()
    
         ' you selects a folder and clicks OK
        If folderBrowserDialog1.ShowDialog() = DialogResult.OK Then
    
            ' get the selected folder path
            Dim folderPath As String = folderBrowserDialog1.SelectedPath
    
    
            ' create the file path by combining the folder path and the file name
            Dim fileName As String = Path.Combine(folderPath, "louietot.txt")
    
            ' append the contents of TextBox1 to the file and add on new line
            Dim newText As String = Environment.NewLine & TextBox1.Text
            System.IO.File.AppendAllText(fileName, newText)
        End If
    End Sub

    Edit: also I am just thinking now...... if you want to click that button4 multiples times and you need to know is if for the first click or 2nd clicks onwards you maybe have to implement something like a click counter... or maybe have 3 buttons
    Last edited by schoemr; Jan 4th, 2023 at 01:46 AM.

  21. #21
    Frenzied Member
    Join Date
    Apr 2016
    Posts
    1,415

    Re: How to create txt file and append text to existing txt file?

    I actually think my click counter idea will work better:


    Code:
    Private clickCount As Integer = 0
    
    Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
        ' Increment the click count
        clickCount += 1
    
        ' declare a FolderBrowserDialog object
        Dim folderBrowserDialog1 As New FolderBrowserDialog()
    
        ' selects a folder and clicks OK
        If folderBrowserDialog1.ShowDialog() = DialogResult.OK Then
    
    
            ' get the selected folder path
            Dim folderPath As String = folderBrowserDialog1.SelectedPath
    
            'create the file path by combining the folder path and the file name
            Dim fileName As String = Path.Combine(folderPath, "louietot.txt")
    
            If clickCount = 1 Then
    
    
                'write textbox1 to the file
                System.IO.File.WriteAllText(fileName, TextBox1.Text)
          
      Else
    
                'append the text of textbox1 to the file witn new line
                Dim newText As String = Environment.NewLine & TextBox1.Text
                System.IO.File.AppendAllText(fileName, newText)
            End If
        End If
    End Sub

  22. #22
    PowerPoster Poppa Mintin's Avatar
    Join Date
    Mar 2009
    Location
    Bottesford, North Lincolnshire, England.
    Posts
    2,429

    Re: How to create txt file and append text to existing txt file?

    Thanks Schoemr,

    Nice to see someone actually helping Max.

    Might I suggest instead of a counter...

    Code:
    Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
        Static clicked as Boolean
    
        ' etc.
    
        If clicked Then
    
        ' etc.
    
        End If
        ' Invert clicked
        clicked = Not clicked
    
        ' etc.
    I think doing it this way will ensure alternate 1st and 2nd clicks.

    Poppa
    Along with the sunshine there has to be a little rain sometime.

  23. #23
    PowerPoster PlausiblyDamp's Avatar
    Join Date
    Dec 2016
    Location
    Pontypool, Wales
    Posts
    2,473

    Re: How to create txt file and append text to existing txt file?

    Quote Originally Posted by maxtertj View Post
    Sorry for that.

    This is what I'm saying.
    I copied this code and paste it on my form

    Code:
    Imports System.IO
    Public Class _29FileClass
    
    
    
    
        Public Class Test
            Public Shared Sub Main()
                Dim path As String = "C:\Users\AMIZOZ\Downloads\Study\Study\bin\Debug\louietot.txt"
                If File.Exists(path) = False Then
                    ' Create a file to write to.
                    Using sw As StreamWriter = File.CreateText(path)
                        sw.WriteLine("Hello")
                        sw.WriteLine("And")
                        sw.WriteLine("Welcome")
                    End Using
                End If
    
                ' Open the file to read from.
                Using sr As StreamReader = File.OpenText(path)
                    Do While sr.Peek() >= 0
                        Console.WriteLine(sr.ReadLine())
                    Loop
                End Using
            End Sub
        End Class
    End Class
    I don't know where to put that code so I just paste it directly.
    The button1 doesn't have any code.

    So I'm confuse how the code provided from your suggestion will work.
    If you want code to execute when you click your button then you need to put the code in the button's click event.

    If you use a StreamWriter then one of the Constructors will take care of creating the file and appending to an existing file.

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width