ASP.NET File 函数不适用于 MemoryStream,但如果复制到临时文件,它可以

问题描述

以下代码有效:

MemoryStream s = TarCreator.CreateTar(todownload);
string path = Path.GetTempFileName();
using (var newFile = System.IO.File.OpenWrite(path))
    s.copyTo(newFile);
return File(System.IO.File.OpenRead(path),MimeTypes.MimeTypeMap.GetMimeType(".tar"),"test.tar");

如果我将其更改为直接使用 MemoryStream,它将不起作用,并显示 500 内部服务器错误

return File(TarCreator.CreateTar(todownload),"test.tar");

我的CreateTar函数如下:

public static Stream CreateTar (string dir)
{
    MemoryStream stream = new();
    using (Tararchive tararchive = Tararchive.CreateOutputTararchive(stream))
    {
        tararchive.IsstreamOwner = false;
        tararchive.RootPath = dir.Replace('\\','/');
        if (tararchive.RootPath.EndsWith("/"))
            tararchive.RootPath = tararchive.RootPath.Remove(tararchive.RootPath.Length - 1);
        AddDirectoryFilesToTar(tararchive,dir);
    }
    return stream;
}

解决方法

在返回之前调用 stream.Position = 0(或者如果有原因 CreateTar 应该返回一个指向自身末尾的流,请将其捕获到一个变量中并在将其传递到 {{ 1}})