【问题标题】:vb.net Reading from a .txt file and displaying the contentsvb.net 从 .txt 文件中读取并显示内容
【发布时间】:2014-08-27 14:27:40
【问题描述】:

我正在制作一个简单的程序来读写 .txt 文件。我有程序可以写入并保存一个 .txt 文件,但是我在读取 .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 文件测试过它,因为我在这个阶段没有进行错误检查。非常感谢您的帮助!

【问题讨论】:

    标签: vb.net file streamreader


    【解决方案1】:

    ListBox 不是用于显示文本,而是用于显示列表(顾名思义)。如果要显示文本,请使用TextBox。由于文件可能包含多行,您可以将.Multiline 属性设置为True,以便TextBox 正确显示。

    此外,在处理Streams时应该使用using statement

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

    或者直接使用System.IO.File.ReadAllText("path to file here") 命令。

    【讨论】:

    • 非常感谢,刚刚用文本框替换了列表框,并对使用部分进行了更改,它就像我想要的那样工作。
    【解决方案2】:

    是否要逐行读取文件并填充列表框控件?

    如果是这种情况,请尝试此功能

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-01-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多