c# - 将 MemoryStream 复制到 FileStream 并保存文件?

标签 c# file-upload filestream memorystream

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

这是我的代码

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
            }
        }
    }
}

最佳答案

复制前需要重新设置流的位置。

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

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

关于c# - 将 MemoryStream 复制到 FileStream 并保存文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18766055/

相关文章:

csv - SQL 2012 FileTable中存储的150MB CSV文件-如何查询要插入表中的数据

c# - Entity Framework Core 映射相关实体,仅当它不为空时

http - 使用 SIRIS 上传文件失败

node.js - 使用nodejs lambda的S3文件上传问题

c - 从文件流读取值并将其存储到可变大小数组中 - OpenGL 和 C

c# - 如何将字节 block 读入结构

c# - 在 GridView 中显示增量数据的最佳方式是什么?

c# - 在互联网上的两台计算机之间建立连接

c# - 将文本文件的编码从 ANSI 更改为 UTF8,而不影响 C# 中文件的任何字符!

c# - 使用 MVC3 以相同的形式上传多个图像