Members

Technology Zones

IBM Learning Center

Articles

Hosted By

MaximumASP

Info

Rated
Read 78,862 times

Related Categories

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

James first started writing tutorials on Visual Basic in 1999 whilst starting this website (then known as VB Web). Since then, the site has grown rapidly, and James has written numerous tutorials, articles and reviews on VB, PHP, ASP and C#. In October 2003, James formed the company Developer Fusion Ltd, which owns this website, and also offers various development services. In his spare time, he's a 3rd year undergraduate studying Computer Science in the UK. He's also a Visual Basic MVP.

Comments