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);

You might also like...

Comments

James Crowley James first started this website when learning Visual Basic back in 1999 whilst studying his GCSEs. The site grew steadily over the years while being run as a hobby - to a regular monthly audience ...

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“C++ : Where friends have access to your private members.” - Gavin Russell Baker