I'm trying to write code to remove the _MAXOSX
folder from a zip archive if it exists (breaks validation further down the line if it exists).
The code must return a byte[]
and not the ZipArchive itself. The code I currently have is:
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.");
}
}
It's not clear to me once I've deleted the entry how I set fileBytes
to the byte array of the updated ZipArchive.
The docs for Update
mode state:
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.
It seems that you will need to obtain the updates bytes after the ZipArchive
has been disposed of:
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();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.