Search code examples
vb.netfilestreamstreamreader

VB.net Multiple StreamReader and FileStream in a single button


I want to create multiple of these readers but my program only reads the first filestream is there a way for it to read them all? or do i have to place them in different buttons? here is my current code, :

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


Solution

  • Not a direct answer to your question (and there's nothing obvious to me in your posted code as to why it's only executing the first reader), but since you're reading text files it'd be a lot less code to use File.ReadAllLines(fileName), like this:

    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) returns an array that has each line of the text file as an element. Much simpler than creating the stream, peeking your way through and reading each line into a list and then converting it to an array.