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

后端 未结 10 2279
我寻月下人不归
我寻月下人不归 2020-11-22 03:06

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

10条回答
  •  悲&欢浪女
    2020-11-22 03:48

    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:

    /// 
    /// Copies the contents of input to output. Doesn't close either stream.
    /// 
    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.

提交回复
热议问题