Using 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
On the line marked, how can I pass the path of the selected file into the开发者_JAVA技巧 StreamReader constructor? Thanks!
Edit: Amended my sample code as per Hans suggestion.
Just use the FileName
property of the OpenFileDialog
class as:
If openFileDialog1.ShowDialog() = DialogResult.OK Then
Using sr As StreamReader = New StreamReader(openFileDialog1.FileName)
' do stuff
End Using
End If
Edit: Though I just saw that you've got MultiSelect
set to True
, so you'd have to use the FileNames
property instead and loop through it and open the StreamReader
for each file.
So something like:
If openFileDialog1.ShowDialog() = DialogResult.OK Then
For Each file As String In openFileDialog1.FileNames
Using sr As StreamReader = New StreamReader(file)
' do stuff
End Using
Next
End If
精彩评论