# Visual Basic > Visual Basic .NET > VS 2010 How to create txt file and append text to existing txt file?

## maxtertj

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.



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

----------


## Poppa Mintin

Hi Maxtertj,

I'd use something like this...


```
 If My.Computer.FileSystem.FileExists(filePath) Then
            FileOpen(1, filePath, OpenMode.Append)
```

Poppa

----------


## .paul.

> Hi Maxtertj,
> 
> I'd use something like this...
> 
> 
> ```
>  If My.Computer.FileSystem.FileExists(filePath) Then
>             FileOpen(1, filePath, OpenMode.Append)
> ```
> ...


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

----------


## maxtertj

What could be the right code I can use?

----------


## .paul.

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

----------


## .paul.

https://learn.microsoft.com/en-us/do...e?view=net-7.0

----------


## PlausiblyDamp

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.

----------


## .paul.

Thats

https://learn.microsoft.com/en-us/do...r?view=net-7.0

----------


## maxtertj

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

----------


## ChrisE

> 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

----------


## ivansmo

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

----------


## Poppa Mintin

> 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

----------


## .paul.

> 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

----------


## maxtertj

> 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  :Frown: 
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.

----------


## .paul.

> 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#

----------


## jmcilhinney

> 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.

----------


## maxtertj

> 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?

----------


## PlausiblyDamp

> 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!

----------


## maxtertj

Sorry for that.

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



```
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.

----------


## schoemr

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:



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



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



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

----------


## schoemr

I actually think my click counter idea will work better:




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

----------


## Poppa Mintin

Thanks Schoemr,

Nice to see someone actually helping Max.

Might I suggest instead of a counter...



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

----------


## PlausiblyDamp

> Sorry for that.
> 
> This is what I'm saying.
> I copied this code and paste it on my form
> 
> 
> 
> ```
> Imports System.IO
> ...


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.

----------

