2014-08-27 251 views
1

我正在製作一個讀取和寫入.txt文件的簡單程序。我有程序寫入並保存.txt文件,但是我從.txt文件讀取時遇到了一些麻煩。下面是我到目前爲止有:vb.net從.txt文件讀取並顯示內容

Using openTxt As New OpenFileDialog() 
    If openTxt.ShowDialog() = Windows.Forms.DialogResult.OK Then 
     Dim displayForm As New Form 
     Dim textReader As New System.IO.StreamReader(openTxt.FileName) 
     displayForm.ListBox1.Text = textReader.ReadToEnd 
     textReader.Close() 
     displayForm.Show() 
    Else 
     MessageBox.Show("Not a text file") 
    End If 
End Using 

當文本已經閱讀它填充列表框中這是目前另一種形式(displayForm)裏面是什麼我想發生這樣的。我試圖讓文本顯示在同一個表單上的列表框中,看看它是否可能改變了任何東西,但它仍然是空白的。我可以確認,我只用.txt文件測試過它,因爲在這個階段我沒有檢查錯誤。非常感謝您的幫助!

回答

4

A ListBox不用於顯示文本,但顯示列表(顧名思義)。如果您要顯示文字,請使用TextBox。由於該文件可能包含多行,因此可以將.Multiline屬性設置爲True,以便TextBox將正確顯示它。

此外,你應該Streams

Dim content As String = "" 
Using textReader As New System.IO.StreamReader(openTxt.FileName) 
    content = textReader.ReadToEnd 
End Using 
displayForm.ListBox1.Text = content 

打交道時使用using statement或簡單地使用System.IO.File.ReadAllText("path to file here")命令。

+0

非常感謝你,只是換了一個文本框列表框,並更改了使用部分它的工作方式就像我希望的那樣。 – Novastorm 2014-08-27 14:48:11

0

是否要逐行讀取文件並填充列表框控件?

如果當時的情況下嘗試這個功能

Function ReadFile(ByVal Filename As String) As String() 
    Dim Sl As New List(Of String) 
    Using Sr As New StreamReader(Filename) 
     While Sr.Peek >= 0 
      Sl.Add(Sr.ReadLine()) 
     End While 
    End Using 
    Return Sl.ToArray 
End Function 

並使用像這樣:

For Each Line As String In ReadFile("FILENAME.txt") 
     ListBox1.Items.Add(Line) 
    Next 
相關問題