Posted by craig
Wednesday, April 22, 2009 10:53:13 AM
Writing from Stream to another Stream in C# .NET
The situation often arises where we want to copy a stream to another without reading the entire stream into memory, here is a simple code snippet to do the trick: /// <summary>
/// Writes the stream to target.
/// </summary>
/// <param name="bufSize">Size of the buf.</param>
/// <param name="inputStream">The input stream.</param>
/// <param name="targetStream">The target stream.</param>
public static void WriteStreamToStream(int bufSize, Stream inputStream, Stream targetStream)
{
byte[] buffer = new byte[bufSize];
long count = 0;
while(inputStream.Length >count)
{
int numBytesRead = inputStream.Read(buffer, 0, bufSize);
targetStream.Write(buffer, 0, numBytesRead);
count += numBytesRead;
}
}
Copyright 2009 AnyTime