microchipj13 microchipj13 - 3 months ago 45
Vb.net Question

How to write a List(of) to a text file and retrieve it (vb.net)

Title. I need to write my ListOf, which just contains values such as Zero, Zero, One, One, Two, etc to a text file, and then load back up again. Any help appreciated!

Answer

Hello & Welcome to Stack Overflow!.

In the future please show some effort when asking a question and at least google or even bing your question first, there are a stack of tutorials regarding your question.

With that being said, I am going to give you a lifeline.
From what I can tell, you want to write your list to a text file and then read from that text file.

Module Module1
Dim mylist As List(Of String) = New List(Of String)
Dim desktopPath As String = Environment.GetFolderPath(Environment.SpecialFolder.Desktop)
Dim newfile As String = "myTextFile.txt"
Dim newPath As String = System.IO.Path.Combine(desktopPath, newfile)

Sub Main()
    mylist.Add("Zero")
    mylist.Add("One")
    mylist.Add("Two")
    mylist.Add("Three")
    writer()
End Sub

Sub writer()
    Using sw As New System.IO.StreamWriter(newPath)
        For Each item As String In mylist
            sw.WriteLine(item)
        Next
        sw.Flush() ''yeap I'm the sort of person that flushes it then closes it
        sw.Close()
    End Using
    reader()
End Sub

Sub reader()
    Using sr As New System.IO.StreamReader(newPath)
        Console.WriteLine(sr.ReadToEnd)
        sr.Close()
    End Using
    Console.ReadKey()
End Sub
End Module

I didn't put too much effort into this, I will leave the rest up to you, however this should get your well and truly on your way.

This was done with a Console application

Also if you have any problems or even a question or two regarding my answer,

leave a comment and I will do my best to answer you and help you out as I know learning something for the first time can be difficult and you will have lots of questions.

EDIT: If you need to load each value separately eg skip the first 4 lines and only read the 5th line, you should look into learning how to do a loop.

EDIT - Here is what I think you are trying to achieve just from reading your comments.

''Reads whatever is in the newPath Textfile and addes the words to a listbox or wherever is needed.
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
    ListBox1.Items.Clear() ''This is stop double ups.
    Dim myTextFile = System.IO.File.ReadAllLines(newPath)
    For Each word As String In myTextFile
        ListBox1.Items.Add(word) '' change this to mylist if need be 
        ''mylist.Add(word)
    Next
End Sub

This should fix your problem, although you may need to clear the mylist first or even create another array.