How to implement true Stream
out of string
and visa versa?
All I see in answers on SO is this common implementation (How do I generate a stream from a string?):
public static Stream GenerateStreamFromString(string s)
{
var stream = new MemoryStream();
var writer = new StreamWriter(stream);
writer.Write(s);
writer.Flush();
stream.Position = 0;
return stream;
}
Obviously, this create memory pressure - a full copy in another format, not much, but still. All depends on usage of stream and size of data. If this stream is used for few starting bytes and some conditioning on those bytes - its just overkill to decode/encode entire string. So, its becoming hard to actually pipeline stream one into another and create iteration over bytes.
So, is there a way? I seem to struggle with Encoding.GetEncoder()/GetDecoder()
because they require char[]
array and can't accept string
.
Another idea is to invert StreamWriter so it will become consumer/producer collection but its just overkill, I think.