将选定的记事本存储到FileStream中

时间:2013-07-10 15:52:17

标签: vb.net filestream streamreader openfiledialog

我目前在将任何选定的记事本文件的内容从openFileDialog存储到FileStream时遇到问题。我的代码声明了一个默认文件名,因为我不知道如何修改FileStream代码,我希望它注册我选择的记事本的文件名。 默认情况下,它只会读取“messages.txt”的内容,我希望可以自由选择任何记事本文件并从中检索数据。任何形式的帮助或建议都会提前感谢。

这是我的代码:

    Dim Stream As New System.IO.FileStream("messages.txt", IO.FileMode.Open) 
    'i need to do something about this line above
    Dim sReader As New System.IO.StreamReader(Stream)
    Dim Index As Integer = 0

    Dim openFileDialog1 As New OpenFileDialog()
    openFileDialog1.InitialDirectory = "D:\work"
    openFileDialog1.Filter = "txt files (*.txt)|*.txt"
    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 While sReader.Peek >= 0
                    ReDim Preserve eArray(Index)
                    eArray(Index) = sReader.ReadLine
                    RichTextBox3.Text = eArray(Index)
                    Index += 1
                    Delay(2)
                Loop

            End If
        Catch Ex As Exception
            MessageBox.Show(Ex.Message)
        Finally
            If (Stream IsNot Nothing) Then
                Stream.Close()
            End If
        End Try
    End If

End Sub

1 个答案:

答案 0 :(得分:0)

我稍微重新安排了你的代码。基本上你是在创建一个流,然后为流创建“messages.txt”的阅读器。稍后,您可以根据文件打开对话框的stream方法将OpenFile对象设置为新流。但是你的读者仍然指向你打开的第一个流,所以这就是读取的内容。我已将以下代码更改为不打开第一个流,并在根据用户选择的文件创建流后创建阅读器。

'don't create a stream hear and the reader, because you are just recreating a stream later in the code
Dim Stream As System.IO.FileStream

Dim Index As Integer = 0

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

If openFileDialog1.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
    Try
        'This line opens the file the user selected and sets the stream object
        Stream = openFileDialog1.OpenFile()
        If (Stream IsNot Nothing) Then
            'create the reader here and use the stream you got from the file open dialog
            Dim sReader As New System.IO.StreamReader(Stream)
            Do While sReader.Peek >= 0
                ReDim Preserve eArray(Index)
                eArray(Index) = sReader.ReadLine
                RichTextBox3.Text = eArray(Index)
                Index += 1
                Delay(2)
            Loop

        End If
    Catch Ex As Exception
        MessageBox.Show(Ex.Message)
    Finally
        If (Stream IsNot Nothing) Then
            Stream.Close()
        End If
    End Try
End If

End Sub