Search code examples
c#dotnetzip

Trying to merge two zip files into 1 using c# and Ionic.dll


Here is the code

ZipFile zipnew = ZipFile.Read(strPath);
if (!File.Exists(path))
{
    using (ZipFile zip = new ZipFile())
    {
        zip.Save(path);
    }
}
    string tmpname = fpath + "\\abtemp";
    ZipFile zipold = ZipFile.Read(path);
    foreach (ZipEntry zenew in zipnew)
    {
        string flna = zenew.FileName.ToString();
        string tfn = '@' + flna.Replace("\\", "/");
        Stream fstream = File.Open(tmpname, FileMode.OpenOrCreate, FileAccess.Write);
        zenew.Extract(fstream);
        string l = fstream.Length.ToString();
        fstream.Close();

        using (StreamReader sr = new StreamReader(tmpname))
        {
            var zn = zipold.UpdateEntry(flna, sr.BaseStream);
            sr.Close();
            sr.Dispose();
            fstream.Dispose();
        }
    }

    zipnew.Dispose();
    File.Delete(tmpname);
    File.Delete(strPath);

The problem is: I get no error and there are no files merged into zipold from zipnew. Zipold is a blank zip file


Solution

  • You're code isn't 100% clear to me, the variable tfn doesn't seem to be used and i'm not quite following with all the disposes / deletes.
    But on the bright side i did get your code working, the main problem was that you're not calling the save method of zipold.

        string path = "d:\\zipold.zip";
        ZipFile zipnew = ZipFile.Read("d:\\zipnew.zip");
        if (!File.Exists(path))
        {
            using (ZipFile zip = new ZipFile())
            {
                zip.Save(path);
            }
        }
        string tmpname = "d:" + "\\temp.dat";
        ZipFile zipold = ZipFile.Read(path);
        foreach (ZipEntry zenew in zipnew)
        {
            string flna = zenew.FileName.ToString();
            //string tfn = '\\' + flna.Replace("\\", "/"); useless line
            Stream fstream = File.Open(tmpname, FileMode.OpenOrCreate, FileAccess.Write);
            zenew.Extract(fstream);
            string l = fstream.Length.ToString();
            fstream.Close();
            using (StreamReader sr = new StreamReader(tmpname))
            {
                var zn = zipold.UpdateEntry(flna, sr.BaseStream);
                zipold.Save();
                sr.Close();
                sr.Dispose();
                fstream.Dispose();
            }
    
        }
        zipnew.Dispose();