将 MemoryStream 复制到 FileStream 并保存文件? [英] Copy MemoryStream to FileStream and save the file?

查看:215
本文介绍了将 MemoryStream 复制到 FileStream 并保存文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不明白我在这里做错了什么.我生成了几个内存流,在调试模式下我看到它们被填充.但是,当我尝试将 MemoryStream 复制到 FileStream 以保存文件时,fileStream 未填充且文件长度为 0 字节(空).

I don't understand what I'm doing wrong here. I generate couple of memory streams and in debug-mode I see that they are populated. But when I try to copy MemoryStream to FileStream in order to save the file fileStream is not populated and file is 0bytes long (empty).

这是我的代码

if (file.ContentLength > 0)
{
    var bytes = ImageUploader.FilestreamToBytes(file); // bytes is populated

    using (var inStream = new MemoryStream(bytes)) // inStream is populated
    {
        using (var outStream = new MemoryStream())
        {
            using (var imageFactory = new ImageFactory())
            {
                imageFactory.Load(inStream)
                            .Resize(new Size(320, 0))
                            .Format(ImageFormat.Jpeg)
                            .Quality(70)
                            .Save(outStream);
            }
            
            // outStream is populated here
            
            var fileName = "test.jpg";

            using (var fileStream = new FileStream(Server.MapPath("~/content/u/") + fileName, FileMode.CreateNew, FileAccess.ReadWrite))
            {
                outStream.CopyTo(fileStream); // fileStream is not populated
            }
        }
    }
}

推荐答案

复制前需要重置流的位置.

You need to reset the position of the stream before copying.

outStream.Position = 0;
outStream.CopyTo(fileStream);

您在使用 imageFactory 保存文件时使用了 outStream.该函数填充了 outStream.在填充 outStream 时,位置被设置为填充区域的末端.这样一来,当您继续向 Steam 写入字节时,它不会覆盖现有字节.但是要阅读它(用于复制目的),您需要将位置设置为开头,以便您可以从头开始阅读.

You used the outStream when saving the file using the imageFactory. That function populated the outStream. While populating the outStream the position is set to the end of the populated area. That is so that when you keep on writing bytes to the steam, it doesn't override existing bytes. But then to read it (for copy purposes) you need to set the position to the start so you can start reading at the start.

这篇关于将 MemoryStream 复制到 FileStream 并保存文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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