如何在 vb.net 中使用 openfiledialog 打开文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15495078/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to open a file using openfiledialog in vb.net?
提问by KARTHIK K
How to open a file using openfiledialog
如何使用 openfiledialog 打开文件
The below is my code:
下面是我的代码:
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)
I can get the path of the file. But not able to open file. Can anyone help. Thanks in advance
我可以得到文件的路径。但无法打开文件。任何人都可以帮忙。提前致谢
回答by Mash
If you want to read the entire text file, you can use System.IO.File.ReadAllLines
. You can do so like this:
如果要阅读整个文本文件,可以使用System.IO.File.ReadAllLines
. 你可以这样做:
Dim readText() As String = System.IO.File.ReadAllLines(path)
The file will then get stored into your string array, and you can access each line by index.
然后该文件将存储到您的字符串数组中,您可以通过索引访问每一行。
回答by SolaGratia
Try this. It should work.
尝试这个。它应该工作。
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