在 C# 中获取 ZipArchive 的字节数组

Get byte array for ZipArchive in C#

我正在尝试编写代码以从 zip 存档中删除 _MAXOSX 文件夹(如果它存在)(如果存在则进一步破坏验证)。

代码必须 return byte[] 而不是 ZipArchive 本身。我目前的代码是:

var fileBytes = uploadController.FileBytes;
if (stripMacOSXFolder && uploadController.FileName.EndsWith(".zip", StringComparison.CurrentCultureIgnoreCase))
{
    try
    {
        using (var data = new MemoryStream(fileBytes))
        using (var archive = new ZipArchive(data, ZipArchiveMode.Update))
        {
            var osx = archive.Entries.SingleOrDefault(c =>
                c.FullName.Equals("__MACOSX/", StringComparison.CurrentCultureIgnoreCase));
            if (osx != null)
            {
                osx.Delete();
                // SET fileBytes to archive byte[]
            }
        }
    }
    catch (Exception)
    {
        return new ObjectReturnMethodResult<UploadedFileV2>("Uploaded zip appears to be invalid.");
    }
}

删除条目后,我不清楚如何将 fileBytes 设置为更新后的 ZipArchive 的字节数组。

docs for Update模式状态:

When you set the mode to Update, the underlying file or stream must support reading, writing, and seeking. The content of the entire archive is held in memory, and no data is written to the underlying file or stream until the archive is disposed.

您似乎需要在处理完 ZipArchive 后获取更新字节:

using (var data = new MemoryStream(fileBytes))
{
    using (var archive = new ZipArchive(data, ZipArchiveMode.Update))
    {
        var osx = archive.Entries.SingleOrDefault(c =>
            c.FullName.Equals("__MACOSX/", StringComparison.CurrentCultureIgnoreCase));
        if (osx != null)
        {
            osx.Delete();
        }
    }
    fileBytes = data.ToArray();
}