使用C#将文件(从流)保存到磁盘 [英] saving a file (from stream) to disk using c#

查看:1170
本文介绍了使用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?

我已经看了(可能不够努力),但是在任何地方都找不到...

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();

这篇关于使用C#将文件(从流)保存到磁盘的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆