如何使用openfiledialog打开文件
以下是我的代码:
Dim Fs As StreamReader
With OpenFD
.FileName = ""
.Title = "Open Text File"
.InitialDirectory = "c:\"
.Filter = "Text files|*.txt"
.ShowDialog()
End With
Dim path As String = OpenFD.FileName
txtin.Text = OpenFD.FileName
Fs = New StreamReader(path)
我可以获取文件的路径。但是无法打开文件。谁能帮忙。 提前致谢
答案 0 :(得分:2)
如果您想阅读整个文本文件,可以使用System.IO.File.ReadAllLines
。你可以这样做:
Dim readText() As String = System.IO.File.ReadAllLines(path)
然后该文件将存储到您的字符串数组中,您可以按索引访问每一行。
答案 1 :(得分:0)
试试这个。它应该工作。
Dim sr As StreamReader
'Supposing you haven't already set these properties...
With OFD
.FileName = ""
.Title = "Open a text file..."
.InitialDirectory = "C:\"
.Filter = "Text Files|*.txt"
End With
If OFD.ShowDialog() = DialogResult.OK Then
Try
sr = New StreamReader(OFD.Filename)
txtInFile.Text = OFD.Filename
Catch ex As Exception
MsgBox("The file specified could not be opened." & VbNewLine & "Error message:" & VbNewLine & VbNewLine & ex.Message, MsgBoxStyle.OK, "File Could Not Be Opened!")
End Try
End If