从我的代码中的文本文件中读取时出现问题

时间:2010-08-31 11:27:58

标签: vb.net

使用Microsoft Visual Studio 2008:

' Create an instance of the open file dialog box.
Dim openFileDialog1 As OpenFileDialog = New OpenFileDialog

' Set filter options and filter index.
openFileDialog1.Filter = "Text Files (*.txt)|*.txt|All Files (*.*)|*.*"
openFileDialog1.FilterIndex = 1

openFileDialog1.Multiselect = True

' Call the ShowDialog method to show the dialogbox.
Dim UserClickedOK As Boolean = openFileDialog1.ShowDialog

' Process input if the user clicked OK.
If (UserClickedOK = True) Then
    Using sr As StreamReader = New StreamReader() ' <-----
        Dim line As String
        ' Read and display the lines from the file until the end 
        ' of the file is reached.
        Do
            line = sr.ReadLine()
            Console.WriteLine(Line)
        Loop Until line Is Nothing
    End Using
End If

在标记的行上,如何将所选文件的路径传递给StreamReader构造函数?谢谢!

1 个答案:

答案 0 :(得分:1)

编辑:根据汉斯的建议修改我的示例代码。

只需使用FileName类的OpenFileDialog属性:

If openFileDialog1.ShowDialog() = DialogResult.OK Then
    Using sr As StreamReader = New StreamReader(openFileDialog1.FileName) 
        ' do stuff
    End Using
End If

编辑:虽然我刚看到您已将MultiSelect设置为True,因此您必须使用FileNames属性并循环浏览并打开{每个文件{1}}。

类似于:

StreamReader