30 November, 2008

Copying an unseekable stream

I came across this issue the other day. I was trying to copy an image from a site into my SharePoint list. The issue was that the Stream that I was receiving was not seekable making it impossible to find out its size. After some awesome google skills and some help from my workmate we came up with a simple solution.

We copy the unseekable stream 64bytes at a time into a new stream making it seekable.

and TADA, this is what you end up with

private static void CopyUnseekableStream(Stream input, Stream output)
{
if (input == null) throw new ArgumentNullException("input");
if (output == null) throw new ArgumentNullException("output");
try
{
using (BinaryWriter bwWriter = new BinaryWriter(output))
using (BinaryReader brReader = new BinaryReader(input))
{
byte[] buf;
do
{
buf = brReader.ReadBytes(1024 * 64); // you can make this any size
bwWriter.Write(buf);
}
while (buf.Length > 0);
bwWriter.Close();
brReader.Close();
}
}
catch (Exception ex)
{

//need to catch errors
}
}
}

No comments: