how to avoid [Content_Types].xml in .net's ZipPackage class

前端 未结 6 1009
星月不相逢
星月不相逢 2021-01-07 19:09

I wish to know if there is any way to avoid to have a [Content_Types].xml file inside the zip file while using .net\'s ZipPackage

6条回答
  •  情深已故
    2021-01-07 19:53

    Yes you can create zip packages without the extra XML content file added

    Inspired by this link: Using System.IO.Packaging to generate a ZIP file

    Using above discovery mentioned by Yiping you can avoid the extra xml file added into the package. Save zip stream from memory stream to a physical zip file before zip archive is closed like this:

    public static void AddFilesToZip(string zipFilename, List filesToAdd)
    {
        using (var memStream = new MemoryStream())
        {
            using (Package zip = System.IO.Packaging.Package.Open(memStream, FileMode.Create))
            {
    
                foreach (var fileToAdd in filesToAdd)
                {
                    string destFilename = ".\\" + Path.GetFileName(fileToAdd);
                    Uri uri = PackUriHelper.CreatePartUri(new Uri(destFilename, UriKind.Relative));
    
                    //Existing parts not likely in fresh memory stream
                    if (zip.PartExists(uri))
                    {
                        zip.DeletePart(uri);
                    }
    
                    PackagePart part = zip.CreatePart(uri, "", CompressionOption.Normal);
    
                    using (FileStream fileStream = new FileStream(fileToAdd, FileMode.Open, FileAccess.Read))
                    {
    
                        using (Stream dest = part.GetStream())
                        {
                            CopyStream(fileStream, dest);
                        }
                    }
                }
    
                //The zip Package will add an XML content type file to memeory stream when it closes
                //so before it closes we save the memorystream to physical zip file.
                using (FileStream zipfilestream = new FileStream(zipFilename, FileMode.Create, FileAccess.Write))
                {
                    memStream.Position = 0;
                    CopyStream(memStream, zipfilestream);
                }
    
                // That's it. Zip file saved to file. Things added by package after this point will be to memory stream finally disposed.
            }
        }
    }
    

提交回复
热议问题