Skip to content

Instantly share code, notes, and snippets.

@partharanjan
Created July 1, 2020 19:08
Show Gist options
  • Save partharanjan/343ce22d5ed5baba8d2d6a447d602809 to your computer and use it in GitHub Desktop.
Save partharanjan/343ce22d5ed5baba8d2d6a447d602809 to your computer and use it in GitHub Desktop.
using System;
using System.IO;
using System.Collections;
namespace Streams
{
public class MultiStream : Stream
{
ArrayList streamList = new ArrayList();
long position = 0;
public override bool CanRead
{
get { return true; }
}
public override bool CanSeek
{
get { return true; }
}
public override bool CanWrite
{
get { return false; }
}
public override long Length
{
get
{
long result = 0;
foreach(Stream stream in streamList)
{
result += stream.Length;
}
return result;
}
}
public override long Position
{
get { return position; }
set { Seek(value, SeekOrigin.Begin); }
}
public override void Flush() {}
public override long Seek(long offset, SeekOrigin origin)
{
long len = Length;
switch(origin)
{
case SeekOrigin.Begin:
position = offset;
break;
case SeekOrigin.Current:
position += offset;
break;
case SeekOrigin.End:
position = len - offset;
break;
}
if(position > len)
{
position = len;
}
else if(position < 0)
{
position = 0;
}
return position;
}
public override void SetLength(long value) {}
public void AddStream(Stream stream)
{
streamList.Add(stream);
}
public override int Read(byte[] buffer, int offset, int count)
{
long len = 0;
int result = 0;
int buf_pos = offset;
int bytesRead;
foreach(Stream stream in streamList)
{
if(position < (len + stream.Length))
{
stream.Position = position - len;
bytesRead = stream.Read(buffer, buf_pos, count);
result += bytesRead;
buf_pos += bytesRead;
position += bytesRead;
if(bytesRead < count)
{
count -= bytesRead;
}
else
{
break;
}
}
len += stream.Length;
}
return result;
}
public override void Write(byte[] buffer, int offset, int count)
{
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment