Search code examples
c#asp.netstreamfilestreammemorystream

ASP.NET File function doesn't works with MemoryStream but if copied to temp file, it does


The following code works:

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

If I change it to use the MemoryStream directly, it does not work and gives me a 500 Internal server error.

return File(TarCreator.CreateTar(toDownload), MimeTypes.MimeTypeMap.GetMimeType(".tar"), "test.tar");

My CreateTar function is as follows:

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

Solution

  • Call stream.Position = 0 before you return it (or if there is a reason CreateTar should return a stream that is pointing to the end of itself, capture it into a variable and reset the position before you pass it into File(...))