2

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.

Sandro Paetzold
  • 123
  • 3
  • 9

1 Answers1

6

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
TypeIA
  • 16,916
  • 1
  • 38
  • 52
  • Are there any issues with leaving Stream open? I need to use the leaveOpen for `HttpContext.Request.EnableRewind()` for a .net core project. I just wanted to know whether there are any implications... – user007 May 14 '18 at 19:38
  • 1
    The _only_ effect of setting the `leaveOpen` flag is to stop `StreamReader.Dispose()` from calling `Dispose()` on the underlying stream. Otherwise the "implications" of leaving the stream open are the same as they would be in any other situation. – TypeIA May 15 '18 at 14:24
  • that overload is only available since .NET 4.5 though – phuclv Aug 20 '19 at 09:43