读取文本文件,然后将所有行添加到 VB.NET 中的列表框中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20290084/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 17:18:58  来源:igfitidea点击:

Read a text file and then add all lines to list box in VB.NET

vb.net

提问by user3024698

I have a text file in my desktop...

我的桌面上有一个文本文件...

In this file we have five lines:

在这个文件中,我们有五行:

Line 1
Line 2
Line 3
Line 4
Line 5

If the user choose this text file then all lines (five lines) add to list box items.

如果用户选择此文本文件,则所有行(五行)都添加到列表框项目中。

For example, we have these in the list box (when the user choose the text file (which it has five lines)):

例如,我们在列表框中有这些(当用户选择文本文件(它有五行)时):

Line 1
Line 2
Line 3
Line 4
Line 5

回答by SysDragon

Try this:

尝试这个:

Dim lines() As String = IO.File.ReadAllLines("C:\dir\file.txt")
ListBox1.Items.AddRange(lines)

More information is at MSDN.

更多信息在 MSDN

回答by user3437514

Private Sub OpenList()
    Dim openfile = New OpenFileDialog()
    openfile.Filter = "Text (*.txt)|*.txt"
    If (openfile.ShowDialog() = System.Windows.Forms.DialogResult.OK) Then
        Dim myfile As String = openfile.FileName
        Dim allLines As String() = File.ReadAllLines(myfile)
        For Each line As String In allLines
            listBox.Items.Add(line)
        Next
    End If
End Sub

回答by Entire

Use:

用:

Dim openfile = New OpenFileDialog() With {.Filter = "Text (*.Text)|*.txt"}
If (openfile.ShowDialog() = System.Windows.Forms.DialogResult.OK) Then
    For Each line As String In File.ReadAllLines(openfile.FileName)
        ListBox1.Items.Add(line)
    Next
End If

Code is a lot better.

代码好多了。