2

如何使用 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)

我可以得到文件的路径。但无法打开文件。任何人都可以帮忙。提前致谢

4

3 回答 3

2

如果要阅读整个文本文件,可以使用System.IO.File.ReadAllLines. 你可以这样做:

Dim readText() As String = System.IO.File.ReadAllLines(path)

然后该文件将存储到您的字符串数组中,您可以按索引访问每一行。

于 2013-03-26T18:24:51.657 回答
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
于 2013-03-25T19:21:51.860 回答
0

不要使用流来读取文本文件,只需使用 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
于 2022-01-15T12:24:39.380 回答