Vb.net 将选定记事本的内容存储到FileStream
我目前在将任何选定记事本文件的内容从openFileDialog存储到FileStream时遇到问题。我的代码声明了一个默认文件名,因为我不知道如何修改FileStream代码,我希望它注册我所选记事本的文件名。 默认情况下,它将只读取“messages.txt”的内容,我想有自由选择任何记事本文件并从中检索数据。任何形式的帮助或建议都会提前表示感谢 这是我的密码:Vb.net 将选定记事本的内容存储到FileStream,vb.net,filestream,streamreader,openfiledialog,Vb.net,Filestream,Streamreader,Openfiledialog,我目前在将任何选定记事本文件的内容从openFileDialog存储到FileStream时遇到问题。我的代码声明了一个默认文件名,因为我不知道如何修改FileStream代码,我希望它注册我所选记事本的文件名。 默认情况下,它将只读取“messages.txt”的内容,我想有自由选择任何记事本文件并从中检索数据。任何形式的帮助或建议都会提前表示感谢 这是我的密码: Dim Stream As New System.IO.FileStream("messages.txt", IO.Fil
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
我重新整理了一下你的代码。基本上,您是在创建一个流,然后为“messages.txt”流创建读卡器。稍后,根据文件打开对话框的
OpenFile
方法,将stream
对象设置为新流。但是你的读者仍然指向你打开的第一条流,所以这就是阅读的内容。我已经更改了下面的代码,不打开第一个流,并在根据用户选择的文件创建流之后创建读取器
'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
非常感谢,它现在起作用了,你把我从困惑中解救了出来。