【问题标题】:Copy MemoryStream to FileStream and save the file?将 MemoryStream 复制到 FileStream 并保存文件?
【发布时间】:2013-09-16 22:41:28
【问题描述】:

我不明白我在这里做错了什么。我生成了几个内存流,在调试模式下我看到它们已被填充。但是当我尝试将 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 包含图像数据吗?我认为 .Save(outStream); 中的问题你能发布调用堆栈吗?
  • @BassamAlugili 伙计,我检查了调试模式。它的人口。 outStream.Position = 0 是问题所在,我需要设置它。

标签: c# file-upload filestream memorystream


【解决方案1】:

你需要在复制之前重置流的位置。

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

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

【讨论】:

  • 我想知道他为什么需要这个 Position = 0;他只是创建了 outStream 而没有使用;为什么他会得到一个错误的位置?
  • @BassamAlugili 他在使用 imageFactory 保存文件时使用了 outsteam。该功能填充了外线。在填充外流时,位置设置为填充区域的末端。这样当您继续向 Steam 写入字节时,它不会覆盖现有字节。但是要阅读它(出于复制目的),您需要将位置设置为开头,以便您可以从头开始阅读。
  • 感谢非常有用的信息。
【解决方案2】:

如果您的目标只是将内存流转储到物理文件(例如查看内容),则可以一步完成:

System.IO.File.WriteAllBytes(@"C:\\filename", memoryStream.ToArray());

也不需要先设置流位置,因为 .ToArray() 操作明确忽略了这一点,根据https://docs.microsoft.com/en-us/dotnet/api/system.io.memorystream.toarray?view=netframework-4.7.2 下方的@BaconBits 评论。

【讨论】:

【解决方案3】:

CopyTo 的另一种替代方法是WriteTo

优势:

无需重置位置。

用法:

outStream.WriteTo(fileStream);                

Function Description:

将此内存流的全部内容写入另一个流。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-12-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-15
    • 2012-01-27
    • 2014-10-04
    • 1970-01-01
    • 2012-01-29
    相关资源
    最近更新 更多