Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
using System;
using System.IO;
using System.Text;
namespace StringBuilderStream
{
public class StringBuilderStream : Stream
{
public StringBuilder stringBuilder { get; private set; }
public Encoding Encoding { get; private set; }
public StringBuilderStream(Encoding encoding, StringBuilder stringBuilder)
{
this.stringBuilder = stringBuilder;
this.Encoding = encoding;
}
public StringBuilderStream(Encoding encoding)
:this(encoding, new StringBuilder())
{
}
public StringBuilderStream()
: this(Encoding.Default)
{
}
public override string ToString()
{
return stringBuilder.ToString();
}
public override bool CanRead
{
get { return true; }
}
public override bool CanSeek
{
get { return true; }
}
public override bool CanWrite
{
get { return true; }
}
public override void Flush()
{
}
public override long Length
{
get { return stringBuilder.Length; }
}
public override long Position { get; set; }
public override int Read(byte[] buffer, int offset, int count)
{
int remainingLength = stringBuilder.Length - (int)Position;
int actualCount = count < remainingLength ? count : remainingLength;
var chars = new char[actualCount];
stringBuilder.CopyTo((int)Position, chars, 0, actualCount);
var bytes = Encoding.GetBytes(chars);
bytes.CopyTo(buffer, offset);
return actualCount;
}
public override long Seek(long offset, SeekOrigin origin)
{
if (origin == SeekOrigin.Begin)
{
Position = offset;
}
else if (origin == SeekOrigin.Current)
{
Position += offset;
}
else if (origin == SeekOrigin.End)
{
Position = stringBuilder.Length - Position;
}
return Position;
}
public override void SetLength(long value)
{
if (stringBuilder.Length > value)
{
stringBuilder.Length = (int)value;
}
}
public override void Write(byte[] buffer, int offset, int count)
{
if (stringBuilder.Length > Position)
{
stringBuilder.Length = (int)Position;
}
stringBuilder.Append(Encoding.GetString(buffer, offset, count));
Position = stringBuilder.ToString().Length;
}
//You don't need to override BeginWrite/EndWrite, etc., unless you can call subsequent async methods:
//http://blogs.msdn.com/b/pfxteam/archive/2012/04/06/10291582.aspx
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.