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. 05 Jun 2009 at 20:55

    Here's an example that's optimized for getting copying a file from an ASP.NET FileUpload control and keeping it's path.

    string filePath = uploadFile(fileUploadControl.FileContent);
    
    private string uploadFile(Stream serverFileStream)
    {
        string filename = ConfigurationManager.AppSettings["FileUploadTempDir"] + 
            DateTime.Now.ToString("yyyyMMddhhmm") + "_" + 
            Customer.GetCustomerName(CustomerId).Replace(" ", "_") + ".txt";
    
        try
        {
            int length = 256;
            int bytesRead = 0;
            Byte[] buffer = new Byte[length];
    
            // write the required bytes
            using (FileStream fs = new FileStream(filename, FileMode.Create))
            {
                do
                {
                    bytesRead = serverFileStream.Read(buffer, 0, length);
                    fs.Write(buffer, 0, bytesRead);
                }
                while (bytesRead == length);
            }
    
            serverFileStream.Dispose();
            return filename;
        }
        catch (Exception ex)
        {
            lblErrorMessage.Text += "An unexpeded error occured uploading the file. " + ex.Message;
            return string.Empty;
        }
    
    }
    
  2. 24 Feb 2009 at 00:23
    When I pass Response.OutputStream as a readStream parameter to this method it is giving "Specified method is not supported." error in readStream.Read() method. I was trying to save a Response.OutputStream to a file. Please help.
  3. 06 Jun 2008 at 17:23

    Thank's a lot from Mexico City

  4. 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).

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 ...
AddThis

Related discussion

Related podcasts

  • Object-Oriented Programming in Ruby

    In this episode, I talk with Scott Bellware about object-oriented programming in Ruby, and Ruby's object model. This is taken from a private conversation, and the audio quality suffers at times. Much thanks to Scott for allowing this to be released.This episode of the Alt.NET Podcast is bro...

Events coming up

  • Aug 28

    St. Louis Day of .NET

    St. Charles, United States

    Technical conference with be 2 full days of content with over 40 sessions from local and national speakers, with topics such as:•.NET languages: C#, VB.NET•Technologies: WPF, Silverlight, WCF•Development tools: Visual Studio, TFS, Expression Blend

Want to stay in touch with what's going on? Follow us on twitter!