Search code examples
c#azurestreamreaderazure-servicebusrelay

Leave StreamReader without closing Stream


I'm working with the Azure Relay Service at the moment and faced a problem handling the stream. I need to use this service in a synchronous way as it is required by the software which will use this implementation.

I'm opening a stream to the service and reading the data from it with StreamReader(), works fine. But now I must leave the StreamReader without closing the underlying stream as I have to send an answer back to the sender.

The problem is, that I can't leave the StreamReader() without closing the underlying stream and its not posible to reopen the stream to send an answer back.

Any ideas how to solve this problem?

Thanks for your help.


Solution

  • There is an overload of the StreamReader constructor which accepts a bool leaveOpen parameter. Passing true prevents the StreamReader from closing the stream when the StreamReader is disposed.

    leaveOpen

    Type: System.Boolean

    true to leave the stream open after the StreamReader object is disposed; otherwise, false.

    Example, using the default UTF8 encoding and 1024-byte buffer that you get with the simpler StreamReader constructors:

    using (var reader = new StreamReader(stream, Encoding.UTF8, true, 1024, true))
    {
        // use reader
    } // stream will NOT be closed here