I have some data in a string. I have a function that takes a stream as input. I want to provide my data to my function without having to copy the complete string into a stream. Essentially I'm looking for a stream class that can wrap a string and read from it.
The only suggestions I've seen online suggest the StringReader which is NOT a stream, or creating a memory stream and writing to it, which means copying the data. I could write my own stream object but the tricky part is handling encoding because a stream deals in bytes. Is there a way to do this without writing new stream classes?
I'm implementing pipeline components in BizTalk. BizTalk deals with everything entirely with streams, so you always pass things to BizTalk in a stream. BizTalk will always read from that stream in small chunks, so it doesn't make sense to copy the entire string to a stream (especially if the string is large), if I can read from the stream how BizTalk wants it.
Stream
can only copy data. In addition, it deals inbyte
s, notchar
s so you'll have to copy data via the decoding process. But, If you want to view a string as a stream of ASCII bytes, you could create a class that implementsStream
to do it. For example:But, that's a lot of work to avoid "copying" data...
You can prevent having to maintain a copy of the whole thing, but you would be forced to use an encoding that results in the same number of bytes for each character. That way you could provide chunks of data via
Encoding.GetBytes(str, strIndex, byteCount, byte[], byteIndex)
as they're being requested straight into the read buffer.There will always be one copy action per
Stream.Read()
operation, because it lets the caller provide the destination buffer.Here is a proper
StringReaderStream
with following drawbacks:Read
has to be at leastmaxBytesPerChar
long. It's possible to implementRead
for small buffers by keeping internal one charbuff = new byte[maxBytesPerChar]
. But's not necessary for most usages.Seek
, it's possible to do seek, but would be very tricky generaly. (Some seek cases, like seek to beginning, seek to end, are simple to implement. )