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

后端 未结 10 2408
我寻月下人不归
我寻月下人不归 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:45

    //If you don't have .Net 4.0  :)
    
    public void SaveStreamToFile(Stream stream, string filename)
    {  
       using(Stream destination = File.Create(filename))
          Write(stream, destination);
    }
    
    //Typically I implement this Write method as a Stream extension method. 
    //The framework handles buffering.
    
    public void Write(Stream from, Stream to)
    {
       for(int a = from.ReadByte(); a != -1; a = from.ReadByte())
          to.WriteByte( (byte) a );
    }
    
    /*
    Note, StreamReader is an IEnumerable while Stream is an IEnumbable.
    The distinction is significant such as in multiple byte character encodings 
    like Unicode used in .Net where Char is one or more bytes (byte[n]). Also, the
    resulting translation from IEnumerable to IEnumerable can loose bytes
    or insert them (for example, "\n" vs. "\r\n") depending on the StreamReader instance
    CurrentEncoding.
    */
    

提交回复
热议问题