Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations wOOdy-Soft on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Howto: Open file for BinaryReader, read data in sub

Status
Not open for further replies.

GPerk

Programmer
Jul 6, 2002
161
US
How can I open a file as FileStream in one Sub and then read bytes from the file with ReadByte in another Sub?
Here is the code I'm trying:

Private Sub btnGetfile_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnGetfile.Click
Path = txtFilename.Text
Dim fs As New FileStream(Path, FileMode.Open)
Dim br As New BinaryReader(fs)
Loc = 0
ShowBlock()
End Sub

Private Sub btnGoTo_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnGoTo.Click
Loc = txtGoTo.Text
ShowBlock()
End Sub

Private Sub ShowBlock()
Dim B As Byte
Dim L As Long

Try
For L = Loc To Loc+255
B = br.ReadByte
'
' use/process B here
'
Next L
Catch
Beep()
End Try
End Sub

The problem is that br is undefined in Sub ShowBlock.
How can I make br global?
 

Your fs and br *live* only in btnGetfile_Click event and it is NOT *visible* anywhere else, including your ShowBlock() Sub. Their scope is limited to this one event only.

Try to declare them as a Module variables, ie in general declaration of your Form.


Have fun.

---- Andy
 
Ah yes, that does work. Thank you.
But...
Note that the file path and name is now 'hard coded' into the program. When I change the name of the file in txtFilename.Text and click btnGetfile, the program continues to read from the original file.
Any suggestions?


Public Class Form1
Dim Path As String = "C:\FTW\Dump.DGX"
Dim Loc As Long
Dim FileSize As Long
Dim fs As New FileStream(Path, FileMode.Open)
Dim br As New BinaryReader(fs)

Private Sub btnGetfile_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnGetfile.Click
Path = txtFilename.Text
FileSize = FileLen(Path)
Loc = 0
ShowBlock()
End Sub

Private Sub btnGoTo_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnGoTo.Click
Loc = txtGoTo.Text
ShowBlock()
End Sub

Private Sub ShowBlock()
Dim B As Byte
Dim L As Long

Try
For L = Loc To Loc+255
B = br.ReadByte
'
' use/process B here
'
Next L
Catch
Beep()
End Try
End Sub
End Class

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top