How do I save a stream to a file in C#?

I have a StreamReader object that I initialized with a stream, now I want to save this stream to disk (the stream may be a .gif or .jpg or .pdf).

Existing Code:

StreamReader sr = new StreamReader(myOtherObject.InputStream);
  1. I need to save this to disk (I have the filename).
  2. In the future I may want to store this to SQL Server.

I have the encoding type also, which I will need if I store it to SQL Server, correct?


As highlighted by Tilendor in Jon Skeet's answer, streams have a CopyTo method since .NET 4.

var fileStream = File.Create("C:\\Path\\To\\File");
myOtherObject.InputStream.Seek(0, SeekOrigin.Begin);
myOtherObject.InputStream.CopyTo(fileStream);
fileStream.Close();

Or with the using syntax:

using (var fileStream = File.Create("C:\\Path\\To\\File"))
{
    myOtherObject.InputStream.Seek(0, SeekOrigin.Begin);
    myOtherObject.InputStream.CopyTo(fileStream);
}

You must not use StreamReader for binary files (like gifs or jpgs). StreamReader is for text data. You will almost certainly lose data if you use it for arbitrary binary data. (If you use Encoding.GetEncoding(28591) you will probably be okay, but what's the point?)

Why do you need to use a StreamReader at all? Why not just keep the binary data as binary data and write it back to disk (or SQL) as binary data?

EDIT: As this seems to be something people want to see... if you do just want to copy one stream to another (e.g. to a file) use something like this:

/// <summary>
/// Copies the contents of input to output. Doesn't close either stream.
/// </summary>
public static void CopyStream(Stream input, Stream output)
{
    byte[] buffer = new byte[8 * 1024];
    int len;
    while ( (len = input.Read(buffer, 0, buffer.Length)) > 0)
    {
        output.Write(buffer, 0, len);
    }    
}

To use it to dump a stream to a file, for example:

using (Stream file = File.Create(filename))
{
    CopyStream(input, file);
}

Note that Stream.CopyTo was introduced in .NET 4, serving basically the same purpose.