使用C#将文件(从流)保存到磁盘
可能重复:
如何将流保存到文件?
我有一个流对象,它可能是图像或文件(msword,pdf),我决定对两种类型的处理方式非常不同,因为我可能想优化/压缩/调整大小/生成缩略图我调用一种将图像保存到磁盘的特定方法,代码为:
I have got a stream object which may be an image or file (msword, pdf), I have decided to handle both types very differently, as I may want to optimize/ compress / resize / produce thumbnails etc. I call a specific method to save an image to disk, the code:
var file = StreamObject;
//if content-type == jpeg, png, bmp do...
Image _image = Image.FromStream(file);
_image.Save(path);
//if pdf, word do...
我该如何
//multimedia/ video?
我已经看了(可能不够努力),但是在任何地方都找不到...
p>I have looked (not hard enough probably) but I could not find it anywhere...
对于文件类型,您可以依靠FileExtensions;将其写入磁盘时,可以使用 BinaryWriter 。或 FileStream 。
For file Type you can rely on FileExtentions and for writing it to disk you can use BinaryWriter. or a FileStream.
示例(假设您已经有一个流):
Example (Assuming you already have a stream):
FileStream fileStream = File.Create(fileFullPath, (int)stream.Length);
// Initialize the bytes array with the stream length and then fill it with data
byte[] bytesInStream = new byte[stream.Length];
stream.Read(bytesInStream, 0, bytesInStream.Length);
// Use write method to write to the file specified above
fileStream.Write(bytesInStream, 0, bytesInStream.Length);
//Close the filestream
fileStream.Close();