0

我想创建多个这样的阅读器,但我的程序只读取第一个文件流有没有办法读取它们?还是我必须将它们放在不同的按钮中?这是我当前的代码,:

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()

结束子

4

1 回答 1

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)返回一个数组,其中包含文本文件的每一行作为一个元素。比创建流、窥视并将每一行读入列表然后将其转换为数组要简单得多。

于 2013-07-30T08:46:22.977 回答