簡體   English   中英

將 MemoryStream 復制到 FileStream 並保存文件?

[英]Copy MemoryStream to FileStream and save the file?

我不明白我在這里做錯了什么。 我生成了幾個內存流,在調試模式下我看到它們被填充。 但是當我嘗試將MemoryStream復制到FileStream以保存文件時, fileStream未填充且文件長度為 0bytes(空)。

這是我的代碼

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

您在使用outStream保存文件時使用了imageFactory 該函數填充了outStream 在填充outStream ,位置被設置為填充區域的末端。 這樣,當您繼續將字節寫入 Steam 時,它不會覆蓋現有字節。 但是要閱讀它(用於復制目的),您需要將位置設置為開頭,以便您可以從頭開始閱讀。

如果您的目標只是將內存流轉儲到物理文件(例如查看內容) - 可以一步完成:

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

也不需要先設置流位置,因為 .ToArray() 操作明確忽略了這一點,根據https://docs.microsoft.com/en-us/dotnet/api/system.io.memorystream下面的@BaconBits 評論.toarray?view=netframework-4.7.2

CopyTo另一種替代方法是WriteTo

優勢:

無需重置位置。

用法:

outStream.WriteTo(fileStream);                

功能說明:

將此內存流的全部內容寫入另一個流。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM