如何将List(of)写入文本文件并检索它(vb.net)

时间:2016-08-19 11:21:26

标签: vb.net

标题。我需要编写我的ListOf,它只包含零,零,一,一,二等值到文本文件,然后再次加载。任何帮助表示赞赏!

2 个答案:

答案 0 :(得分:3)

Hello&欢迎来到Stack Overflow!。
在未来请在提出问题时给出一些努力,至少谷歌甚至首先提出你的问题,有一堆关于你的问题的教程。

话虽如此,我将给你一条生命线。
据我所知,你想把你的清单写成文本文件,然后从该文本文件中读取。

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

我没有付出太多精力,我会把剩下的东西留给你,但是这应该让你的方式真正顺利。

这是通过控制台应用程序完成的

如果您对我的回答有任何问题或甚至一两个问题,请发表评论,我将尽我所能回答并帮助您知道第一次学习的东西可能很难,你会有很多问题。

编辑:如果你需要分别加载每个值,例如跳过前4行,只读第5行,你应该研究如何做一个循环。

编辑 - 通过阅读您的意见,我认为您正在努力实现这一目标。

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

这可以解决您的问题,但您可能需要先清除mylist,或者甚至创建另一个数组。

答案 1 :(得分:1)

以下是一些沙箱代码:

Imports System.Xml.Serialization
Imports System.IO
Public Class frmTest

    Dim l1 As New List(Of String)

    Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
        l1.AddRange({"1", "b", "7"})
        Dim mySerializer As XmlSerializer = New XmlSerializer(GetType(List(Of String)))
        ' To write to a file, create a StreamWriter object.
        Dim myWriter As StreamWriter = New StreamWriter("C:\temp\list.xml")
        mySerializer.Serialize(myWriter, l1)
        myWriter.Close()
    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim myFileStream As FileStream = New FileStream("C:\temp\list.xml", FileMode.Open)
        Dim mySerializer As XmlSerializer = New XmlSerializer(GetType(List(Of String)))
        ' Call the Deserialize method and cast to the object type.
        l1 = New List(Of String) ' refresh for test
        l1 = CType(mySerializer.Deserialize(myFileStream), List(Of String))
        Stop ' l1 is populated
    End Sub
End Class
相关问题