简体   繁体   English

如何在 vb.net 中使用 openfiledialog 打开文件?

[英]How to open a file using openfiledialog in vb.net?

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提前致谢

If you want to read the entire text file, you can use System.IO.File.ReadAllLines . 如果要读取整个文本文件,则可以使用System.IO.File.ReadAllLines You can do so like this: 您可以这样做:

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. 然后,该文件将存储到您的字符串数组中,并且您可以按索引访问每一行。

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

Do not use a stream to read a text file simply use File.ReadAllText(), here are my codes that work for me不要使用流来读取文本文件,只需使用 File.ReadAllText(),这是我的代码对我有用

Private Sub OpenFileButton_Click(sender As Object, e As EventArgs) Handles OpenFileButton.Click
    OpenFileDialog1.Title = "Please Select TEXT File"
    OpenFileDialog1.Filter = "Text File|*.txt"
    OpenFileDialog1.FileName = "Query"
    If OpenFileDialog1.ShowDialog = DialogResult.OK Then
        RichTextBox1.Text = File.ReadAllText(OpenFileDialog1.FileName)
    End If
End Sub

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM