0

我想在 VB.net 中创建一个按钮,让我浏览我的硬盘驱动器以查找我要打开的指定记事本文件并从中检索内容,我只尝试使用 FileStream 和 StreamReader 但这不会让我手动选择记事本文件而不是我必须声明一个默认文件名。任何示例代码都将不胜感激,我只需要一个起点。我真的坚持这一点。

这是我现在使用的代码,但我必须在上面指定正确的文件名:

        Dim fStream As New System.IO.FileStream("messages.txt", IO.FileMode.Open)
        Dim sReader As New System.IO.StreamReader(fStream)
        Dim Index As Integer = 0
        Do While sReader.Peek >= 0
            ReDim Preserve sArray(Index)
            sArray(Index) = sReader.ReadLine
            Index += 1
        Loop
4

2 回答 2

1

如果我正确理解了您的问题,您希望可以选择打开哪个文本文件,如果是这样,您可以试试这个:

Dim openFileDialog1 As New OpenFileDialog()
openFileDialog1.InitialDirectory = "c:\"
openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*"
openFileDialog1.FilterIndex = 2
openFileDialog1.RestoreDirectory = True

If openFileDialog1.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
    Try
        stream = openFileDialog1.OpenFile()
        If (stream IsNot Nothing) Then
            //do your loop here
        End If
    Catch Ex As Exception
        MessageBox.Show(Ex.Message)
    Finally
        If (stream IsNot Nothing) Then
            stream.Close()
        End If
    End Try
End If
于 2013-07-10T11:39:28.143 回答
0

我认为您可能对 FileStream 使用了错误的方法。而是让用户选择一个文件,然后使用 Process.Start 打开记事本。

在此处查看有关选择文件的示例。然后此处的页面详细说明了 Process.Start。

我很高兴直接在这里提供更多代码示例,但是这两页应该足够了。

于 2013-07-10T11:30:20.363 回答