locked
Passing a streamreader as a parameter to a function? RRS feed

  • Question

  • I have an open binary streamreader and would like to use it in a function, where the function input parameter is a byte offset number. The intention is that the function takes the byte offset and extracts data from that location in the binary file.

    If I use the streamreader name in the function it says it's not declared, because it was opened in a different subroutine.

    Is it possible to pass the open streamreader to the function so that the function can access the file? If so, how do I do this? I assume it would be ByRef but what is the syntax?

    Grateful for advice.

    I'm using VB Express 2008.

    Thursday, May 9, 2013 11:25 AM

Answers

All replies

  • You can pass the StreamReader as an argument to your function. The Function signature would look something like this (I assumed that you are returning the data in a Byte array).

    Function ReadAtOffset(ByVal sr As IO.StreamReader, ByVal offset as Long) As Byte()

    Note that as StreamReader is a reference type, it is not necessary to use ByRef. You would call the function like this

    Dim sr As New IO.StreamReader("myfile.dat") 'Or whatever you file is
    Dim offset As Long = 0
    Dim myData() As Byte = ReadAtOffset(sr, offset)
    Don't forget to close the StreamReader when you are finished with it.


    • Edited by Blackwood Thursday, May 9, 2013 11:59 AM
    Thursday, May 9, 2013 11:57 AM

  • Is it possible to pass the open streamreader to the function so that the function can access the file? If so, how do I do this? I assume it would be ByRef but what is the syntax?


    Hi,

    'Alter the return type to suit your needs:>>
    Private Function SomeFunction(ByRef sr as System.Io.StreamReader) As System.Object
    
    End Function
    
    'As a SUB:>>
    Private Sub SomeSub(ByRef sr as System.Io.StreamReader)
    
    End Sub
    


    Regards,

    profile for John Anthony Oliver at Stack Overflow, Q&A for professional and enthusiast programmers

    Click this link to see the NEW way of how to insert a picture into a forum post.

    Installing VB6 on Windows 7

    App Hub for Windows Phone & XBOX 360 developers.

    • Marked as answer by Anonymous126 Thursday, May 9, 2013 12:23 PM
    Thursday, May 9, 2013 11:57 AM
  • Thanks. This worked perfectly. I knew it had to be possible.

    Regards

    Thursday, May 9, 2013 12:24 PM