Library code snippets

Save a Stream to a File

If you've got a Stream in .NET - whether its fetched from a HttpWebRequest or read from another file - you can easily save this stream to another file using the following code.

// readStream is the stream you need to read
// writeStream is the stream you want to write to
private void ReadWriteStream(Stream readStream, Stream writeStream)
{
    int Length = 256;
    Byte [] buffer = new Byte[Length];
    int bytesRead = readStream.Read(buffer,0,Length);
    // write the required bytes
    while( bytesRead > 0 )
    {
        writeStream.Write(buffer,0,bytesRead);
        bytesRead = readStream.Read(buffer,0,Length);
    }
    readStream.Close();
    writeStream.Close();
}

To call this method, just do something like this:

string saveTo = "some path to save"
// create a write stream
FileStream writeStream = new FileStream(saveTo, FileMode.Create, FileAccess.Write);
// write to the stream
ReadWriteStream(readStream,writeStream);

Comments

  1. 06 Jun 2008 at 17:23

    Thank's a lot from Mexico City

  2. 01 Jan 1999 at 00:00

    This thread is for discussions of Save a Stream to a File.

Leave a comment

Sign in or Join us (it's free).

AddThis

Related podcasts

  • Looking into the C# Crystal Ball with Charlie Calvert and Bill Wagner

    One of the most exciting announcements from PDC was the news about C# 4.0 and Visual Studio 2010. With all the excitement and discussion throughout the event about these new developer tools, we reached out to two experts in the fields. Charlie Calvert and Bill Wagner sat down with Keith and Woody...

Events coming up

  • Jun 16

    Code Generation 2009

    Cambridge, United Kingdom

    A developer event with a practical focus on helping people get to grips with code generation tools and technologies.