Skip to content

Instantly share code, notes, and snippets.

@alanmcgovern
Created February 7, 2014 15:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alanmcgovern/b7b698a65538db83d810 to your computer and use it in GitHub Desktop.
Save alanmcgovern/b7b698a65538db83d810 to your computer and use it in GitHub Desktop.
using System;
using System.IO;
namespace Workaround
{
// This class worksaround bugs in framework code that assume that the amound of bytes returned by Stream.Read
// is always equal to the length argument they give. It does so by ensuring that this amount is correct.
public class RobustifiedStream : Stream
{
Stream wrappedStream;
public RobustifiedStream (Stream wrappedStream)
{
this.wrappedStream = wrappedStream;
}
public override int Read (byte[] buffer, int offset, int count)
{
int read = 0;
do {
var justRead = wrappedStream.Read (buffer, offset + read, count - read);
// In case nothing could be returned, return immediately to the caller
if (justRead < 1)
return read;
read += justRead;
} while (read < count);
return read;
}
#region Deferred Stream implementation
public override void Flush ()
{
wrappedStream.Flush ();
}
public override long Seek (long offset, SeekOrigin origin)
{
return wrappedStream.Seek (offset, origin);
}
public override void SetLength (long value)
{
wrappedStream.SetLength (value);
}
public override void Write (byte[] buffer, int offset, int count)
{
wrappedStream.Write (buffer, offset, count);
}
public override bool CanRead {
get {
return wrappedStream.CanRead;
}
}
public override bool CanSeek {
get {
return wrappedStream.CanSeek;
}
}
public override bool CanWrite {
get {
return wrappedStream.CanWrite;
}
}
public override long Length {
get {
return wrappedStream.Length;
}
}
public override long Position {
get {
return wrappedStream.Position;
}
set {
wrappedStream.Position = value;
}
}
#endregion
protected override void Dispose (bool disposing)
{
if (disposing)
wrappedStream.Dispose ();
base.Dispose (disposing);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment