buks
buks

Reputation: 435

Modyfing one of files inside zip package

I have some ZIP archive, there is plenty of files/folders. I want to modify some of them/replace their content.

I've found some smaple code on a site: http://docs.telerik.com/devtools/silverlight/controls/radziplibrary/features/update-ziparchive.html

but it is not working, file is not updated.

ZipArchiveEntry stencilEntry = archive.GetEntry(SBSX.StencilEntry.FullName);//entries.Where(c => c.Name == "stencil.xml").FirstOrDefault();
Stream stencilStream = stencilEntry.Open();//archive.GetEntry(SBSX.StencilEntry.FullName);// SBSX.StencilEntry.Open();
using (StreamReader ts = new StreamReader(stencilStream))
{
    XmlDocument xmlDoc = new XmlDocument();
    xmlDoc.LoadXml(ts.ReadToEnd());
    if (xmlDoc.DocumentElement.Name == "Stencil")
    {
        stencilStream.Position = 0;
        Stencil stencil = SupportXML.ReturnObjectFromXML<Stencil>(stencilStream);
        if (SBSX.Display==DisplayType.IconAndName)
        {
            stencil.DefaultControlDisplayStyle = DisplayType.IconAndName.ToString();
        }
        else if (SBSX.Display==DisplayType.IconOnly)
        {
            stencil.DefaultControlDisplayStyle = DisplayType.IconOnly.ToString();
        }

        XmlSerializer serializer = new XmlSerializer(typeof(Stencil));

        using (MemoryStream stream = new MemoryStream())
        {
            serializer.Serialize(stream, stencil);
            stream.Seek(0, SeekOrigin.Begin);

            var sr = new StreamReader(stream);
            var myStr = sr.ReadToEnd();
            stream.Seek(0, SeekOrigin.Begin);

            stencilStream.Seek(0, SeekOrigin.End);
            StreamWriter writer = new StreamWriter(stencilStream);
            writer.Write(myStr);
        }
    }

Could you advise me how to fix it? Or maybe the only solution is to delete ZipArchiveEntry first, and later to Add new ZipArchiveEntry?

Upvotes: 0

Views: 76

Answers (1)

Ben Jackson
Ben Jackson

Reputation: 1138

This should work with a few modifications, providing the zip is opened in Update mode. Is the code definitely being executed?

There are a couple of issues. Firstly you are not flushing your StreamWriter. You should explicitly call Flush after the Write method, otherwise the data may not all actually get written to the stream until the object is finalised, by which time the stream may be closed.

Similarly you are not calling Close on stencilStream, and it's possible that it is this that will trigger the actual update of the ZIP file, though I believe this will get disposed with the outer StreamReader.

Also I assume you're aware that this code would append to the existing file content rather than replacing it? Concatenated XML isn't much use.

Upvotes: 1

Related Questions