writing from One stream to another in C# .NET

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

Thank God! Someone with branis speaks!

Thursday, July 28, 2011 2:01:22 PM Keys
Thank God! Someone with branis speaks!

Thank God! Someone with branis speaks!

Thursday, July 28, 2011 1:59:55 PM Keys
Thank God! Someone with branis speaks!

Thank God! Someone with branis speaks!

Thursday, July 28, 2011 1:58:27 PM Keys
Thank God! Someone with branis speaks!