2

How to open a file using 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

3 Answers 3

2

If you want to read the entire text file, you can use 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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

Do not use a stream to read a text file simply use File.ReadAllText(), here are my codes that work for me

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.