public void SaveStreamToFile(string fileFullPath, Stream stream){if (stream.Length == 0) return;
// Create a FileStream object to write a stream to a fileusing (FileStream fileStream = System.IO.File.Create(fileFullPath, (int)stream.Length)){// Fill the bytes[] array with the stream databyte[] bytesInStream = new byte[stream.Length];stream.Read(bytesInStream, 0, (int)bytesInStream.Length);
// Use FileStream object to write to the specified filefileStream.Write(bytesInStream, 0, bytesInStream.Length);}}
正如Tilendor在Jon Skeet的回答中强调的那样,从. NET 4开始,流就有了CopyTo方法。
var fileStream = File.Create("C:\\Path\\To\\File");myOtherObject.InputStream.Seek(0, SeekOrigin.Begin);myOtherObject.InputStream.CopyTo(fileStream);fileStream.Close();
或者使用using语法:
using (var fileStream = File.Create("C:\\Path\\To\\File")){myOtherObject.InputStream.Seek(0, SeekOrigin.Begin);myOtherObject.InputStream.CopyTo(fileStream);}
//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<Char> while Stream is an IEnumbable<byte>.The distinction is significant such as in multiple byte character encodingslike Unicode used in .Net where Char is one or more bytes (byte[n]). Also, theresulting translation from IEnumerable<byte> to IEnumerable<Char> can loose bytesor insert them (for example, "\n" vs. "\r\n") depending on the StreamReader instanceCurrentEncoding.*/