I see a lot of good answers here, but none that directly address the lack of a StringStream class in C#. So I have written one of my own...
public class StringStream : Stream
{
private readonly MemoryStream _memory;
public StringStream(string text)
{
_memory = new MemoryStream(Encoding.UTF8.GetBytes(text));
}
public StringStream()
{
_memory = new MemoryStream();
}
public StringStream(int capacity)
{
_memory = new MemoryStream(capacity);
}
public override void Flush()
{
_memory.Flush();
}
public override int Read(byte[] buffer, int offset, int count)
{
return _memory.Read(buffer, offset, count);
}
public override long Seek(long offset, SeekOrigin origin)
{
return _memory.Seek(offset, origin);
}
public override void SetLength(long value)
{
_memory.SetLength(value);
}
public override void Write(byte[] buffer, int offset, int count)
{
_memory.Write(buffer, offset, count);
}
public override bool CanRead => _memory.CanRead;
public override bool CanSeek => _memory.CanSeek;
public override bool CanWrite => _memory.CanWrite;
public override long Length => _memory.Length;
public override long Position
{
get => _memory.Position;
set => _memory.Position = value;
}
public override string ToString()
{
return System.Text.Encoding.UTF8.GetString(_memory.GetBuffer(), 0, (int) _memory.Length);
}
public override int ReadByte()
{
return _memory.ReadByte();
}
public override void WriteByte(byte value)
{
_memory.WriteByte(value);
}
}
An example of its use...
string s0 =
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor\r\n" +
"incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud\r\n" +
"exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor\r\n" +
"in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint\r\n" +
"occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.\r\n";
StringStream ss0 = new StringStream(s0);
StringStream ss1 = new StringStream();
int line = 1;
Console.WriteLine("Contents of input stream: ");
Console.WriteLine();
using (StreamReader reader = new StreamReader(ss0))
{
using (StreamWriter writer = new StreamWriter(ss1))
{
while (!reader.EndOfStream)
{
string s = reader.ReadLine();
Console.WriteLine("Line " + line++ + ": " + s);
writer.WriteLine(s);
}
}
}
Console.WriteLine();
Console.WriteLine("Contents of output stream: ");
Console.WriteLine();
Console.Write(ss1.ToString());