C# Zip 返回无效文件

问题描述 投票:0回答:1

我有以下代码将文件名从 Form Post 转换为 zip 并返回它们。 当我运行它时,我得到 .zip 文件,但它无效。有人看到我的错误吗?

public IActionResult OnPost()
{
    Username = HttpContext.Session.GetString("Username");
    string[] FilePaths = Request.Form["FilePath"];
    Dictionary<string, byte[]> fileList = new Dictionary<string, byte[]>();
    byte[] retVal = null;

    foreach (var path in FilePaths)
    {
        string fullPath = Path.Combine(@"C:\Downloads\", Username, path);
        byte[] bytes = System.IO.File.ReadAllBytes(fullPath);
        fileList.Add(path, bytes);
    }

    using (MemoryStream zipStream = new MemoryStream())
    {
        using (ZipArchive archive = new ZipArchive(zipStream, ZipArchiveMode.Create, true))
        {
            foreach (var file in fileList)
            {
                var demoFile = archive.CreateEntry(file.Key);

                using (var entryStream = demoFile.Open())
                using (var b = new BinaryWriter(entryStream))
                {
                    b.Write(file.Value);
                    b.Close();
                }
            }

            zipStream.Position = 0;

        }
        retVal = zipStream.ToArray();
    }
    return File(retVal, MediaTypeNames.Application.Zip, "test.zip");
}
c# razor zip razor-pages
1个回答
0
投票

这段代码对我有用,添加了条件来检查文件是否存在,否则会引发异常。我已经更新了代码。

public IActionResult OnPost()
{
    Username = HttpContext.Session.GetString("Username");
    string[] FilePaths = Request.Form["FilePath"];
    Dictionary<string, byte[]> fileList = new Dictionary<string, byte[]>();
    byte[] retVal = null;

    foreach (var path in FilePaths)
    {
        string fullPath = Path.Combine(@"C:\Downloads\", Username, path);
        if (System.IO.File.Exists(fullPath))
        {
            byte[] bytes = System.IO.File.ReadAllBytes(fullPath);
            fileList.Add(path, bytes);
        }
    }

    using (MemoryStream zipStream = new MemoryStream())
    {
        using (ZipArchive archive = new ZipArchive(zipStream, ZipArchiveMode.Create, true))
        {
            foreach (var file in fileList)
            {
                var demoFile = archive.CreateEntry(file.Key);

                using (var entryStream = demoFile.Open())
                using (var b = new BinaryWriter(entryStream))
                {
                    b.Write(file.Value);
                }
            }
        }
        zipStream.Position = 0;
        retVal = zipStream.ToArray();
    }

    return File(retVal, MediaTypeNames.Application.Zip, "test.zip");
}
© www.soinside.com 2019 - 2024. All rights reserved.