VB.net在一个按钮中有多个StreamReader和FileStream

时间:2013-07-30 08:16:20

标签: vb.net filestream streamreader

我想创建多个这些读者,但我的程序只读取第一个文件流是否有办法让它们全部读取?或者我必须将它们放在不同的按钮中?这是我目前的代码:

Public aRecp As String()
Public listRecp As New List(Of String)
Public aEmail As String()
Public listEmail As New List(Of String)
Public aName As String()
Public listName As New List(Of String)
Public sArray As String()
Public sList As New List(Of String)

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

    Dim fStream As New System.IO.FileStream("messages.txt", IO.FileMode.Open)
    Dim sReader As New System.IO.StreamReader(fStream)
    Dim Index As Integer = 0
    Do While sReader.Peek >= 0
        sList.Add(sReader.ReadLine)
    Loop
    sArray = sList.ToArray
    fStream.Close()
    sReader.Close()

    Dim StreamName As New System.IO.FileStream("sendername.txt", IO.FileMode.Open)
    Dim ReaderName As New System.IO.StreamReader(StreamName)
    Dim IndexName As Integer = 0
    Do While ReaderName.Peek >= 0
        listName.Add(sReader.ReadLine)
    Loop
    aName = listName.ToArray
    StreamName.Close()
    ReaderName.Close()

    Dim StreamEmail As New System.IO.FileStream("senderemail.txt", IO.FileMode.Open)
    Dim ReaderEmail As New System.IO.StreamReader(StreamEmail)
    Dim IndexEmail As Integer = 0
    Do While ReaderEmail.Peek >= 0
        listEmail.Add(sReader.ReadLine)
    Loop
    aEmail = listEmail.ToArray
    StreamEmail.Close()
    ReaderEmail.Close()

    Dim StreamRecp As New System.IO.FileStream("recpname.txt", IO.FileMode.Open)
    Dim ReaderRecp As New System.IO.StreamReader(StreamRecp)
    Dim IndexRecp As Integer = 0
    Do While ReaderRecp.Peek >= 0
        listRecp.Add(ReaderRecp.ReadLine)
    Loop
    aRecp = listRecp.ToArray
    StreamRecp.Close()
    ReaderRecp.Close()

End Sub

1 个答案:

答案 0 :(得分:1)

不能直接回答你的问题(在你发布的代码中没有任何关于它为什么只执行第一个阅读器的内容,但是因为你正在阅读文本文件,所以使用的代码要少得多File.ReadAllLines(fileName),就像这样:

Public aRecp As String()
Public aEmail As String()
Public aName As String()
Public sArray As String()

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

    sArray = File.ReadAllLines("messages.txt")
    aName = File.ReadAllLines("sendername.txt")
    aEmail = File.ReadAllLines("senderemail.txt")
    aRecp = File.ReadAllLines("recpname.txt")
End Sub

File.ReadAllLines(fileName)返回一个数组,该数组将文本文件的每一行作为元素。比创建流更简单,窥视你的方式并将每行读入列表然后将其转换为数组。