将文件添加到vb.net / vb2008的列表框中

时间:2011-08-21 11:59:44

标签: vb.net

您好我将代理存储在notpad.txt文件中,我试图抓取notpad中的所有代理并将它们放入listbox1

我正在使用

Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
    Using Ofd As New OpenFileDialog
        Ofd.Filter = "All files (*.*)|*.*"
        If Ofd.ShowDialog = 1 Then ListBox1.Items.AddRange(IO.File.ReadAllLines(Ofd.FileName))
    End Using
End Sub

我点击它按钮,它让我选择一个文件,但不会将文件中的内容导入listbox1

请帮忙

2 个答案:

答案 0 :(得分:0)

我测试了你的代码,它对我有用,所以我认为问题在于你的文件格式。该文件是如何创建的?你能提供一个链接,以便我看看吗?

有一点需要注意,您应该使用DialogResult Enumeration而不是幻数1来获得OK结果,以提高代码的可读性和维护性。

If Ofd.ShowDialog = DialogResult.OK Then ListBox1.Items.AddRange(IO.File.ReadAllLines(Ofd.FileName))

答案 1 :(得分:0)

尝试此示例如果单击“确定”按钮

,请添加它
    Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
    Using Ofd As New OpenFileDialog
        Ofd.Filter = "All files (*.*)|*.*"

        If Ofd.ShowDialog = 1 Then

            'Pass the file path and file name to the StreamReader constructor
            Dim sr As New StreamReader(Ofd.FileName)
            Dim line As String = String.Empty
            Try
                'Read the first line of text
                line = sr.ReadLine()
                'Continue to read until you reach end of file
                While line IsNot Nothing
                    Me.listBox1.Items.Add(line)
                    'Read the next line
                    line = sr.ReadLine()
                End While

                'close the file
                sr.Close()
            Catch e As Exception
                MessageBox.Show(e.Message.ToString())
            Finally
                'close the file
                sr.Close()
            End Try
        End If
    End Using
End Sub

此致