Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/heroku/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
读取文本文件,然后将所有行添加到VB.NET中的列表框中_Vb.net - Fatal编程技术网

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

读取文本文件,然后将所有行添加到VB.NET中的列表框中,vb.net,Vb.net,我的桌面上有一个文本文件 在此文件中,我们有五行: Line 1 Line 2 Line 3 Line 4 Line 5 Line 1 Line 2 Line 3 Line 4 Line 5 如果用户选择此文本文件,则所有行(五行)都将添加到列表框项目 例如,列表框中有以下内容(当用户选择文本文件时(文本文件有五行)): 试试这个: Dim lines() As String = IO.File.ReadAllLines("C:\dir\file.txt") ListBox1.Items.A

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

在此文件中,我们有五行:

Line 1
Line 2
Line 3
Line 4
Line 5
Line 1
Line 2
Line 3
Line 4
Line 5
如果用户选择此文本文件,则所有行(五行)都将添加到列表框项目

例如,列表框中有以下内容(当用户选择文本文件时(文本文件有五行)):

试试这个:

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

使用:


代码要好得多。

[这个问题已经得到了回答][1][1]:甚至更短:ListBox1.Items.AddRange(IO.File.ReadAllLines(“C:\dir\File.txt”))他要求VB.NET,所以我为你转换了代码。下次注意这个,谢谢!欢迎来到堆栈溢出!考虑扩展一点并解释代码的作用-一块没有解释的代码在将来对询问者没有帮助。谢谢。我之所以发布这篇文章,是因为与上面发布的代码相比,它更容易阅读。下次就可以了。
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
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