2013-07-30 28 views
0

我想創建多個這些閱讀器,但我的程序只讀取第一個文件流有沒有辦法讓它讀取它們?或者我必須將它們放在不同的按鈕中?這裏是我當前的代碼,:VB.net單個按鈕中的多個StreamReader和FileStream

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

末次

+1

你有什麼錯誤嗎?你爲什麼說這段代碼只讀取第一個文件? – Steve

+0

除非您有使用'StreamReader'的特定原因,否則您可以使用'File.ReadAllLines(fileName)'在4行代碼中完成上面相同的代碼。 – Tim

回答

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)返回包含文本文件作爲元素的每一行的數組。比創建流簡單得多,偷看你的方式並將每行讀入列表,然後將其轉換爲數組。

+0

非常感謝這個人,這使得我的程序執行速度更快。我的主要目的是檢索文本文件並將它們放在每行數組中。這是我的問題的答案。 –