mitchellt
mitchellt

Reputation: 1022

Zipping specific files and folders with C# (System.IO.Compression)

I have an archive method for my project which zips specific files.

All of these files are contained inside of the zip but for one of the entries which I have added, rather than add the file, it has added the entire path of folders with the file contained in them.

How I am currently going about it is to create a zip file with one of the directories, then update it with the other files which need adding (they are in different directories).

For example:

ZipFile

What would be ideal is:

ZipFile

Attached Code:

    string zipFileName = "example.zip";
    string zipFile = ArchiveDirectory + "\\" + zipFileName;

    ZipFile.CreateFromDirectory(OutputDirectory, zipFile);

    using (FileStream zipToOpen = new FileStream(zipFile, FileMode.Open))
    {
        using (ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Update))
        {
            ZipArchiveEntry results = archive.CreateEntry(ResultsDirectory);
            ZipArchiveEntry log = archive.CreateEntry(LogPath);
        }
    }

Thanks.

Upvotes: 1

Views: 1960

Answers (1)

Mohamed Salemyan
Mohamed Salemyan

Reputation: 691

I suggest you use ZipStorer Library for easier manage your archive in your project. for example to archive a directory with different files and folders path you do like this:

System.IO.Compression.ZipStorer zip;

zip = System.IO.Compression.ZipStorer.Open(strZipFilePath, FileAccess.Write);

zip.EncodeUTF8 = true;

string path = "C:\\MyRootFolder\\";
string[] arrFiles = Directory.GetFiles(path, "*.*", SearchOption.AllDirectories);
foreach (var item in arrFiles)
{
     string newPath = item.Replace(path, "");
     zip.AddFile(System.IO.Compression.ZipStorer.Compression.Deflate,
                item, newPath, "");
}

Upvotes: 1

Related Questions