Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SharpLibZip: Add file without path

I'm using the following code, using the SharpZipLib library, to add files to a .zip file, but each file is being stored with its full path. I need to only store the file, in the 'root' of the .zip file.

string[] files = Directory.GetFiles(folderPath);
using (ZipFile zipFile = ZipFile.Create(zipFilePath))
{
     zipFile.BeginUpdate();
     foreach (string file in files)
     {
          zipFile.Add(file);
     }
     zipFile.CommitUpdate();
}

I can't find anything about an option for this in the supplied documentation. As this is a very popular library, I hope someone reading this may know something.

like image 730
ProfK Avatar asked Oct 13 '08 17:10

ProfK


2 Answers

My solution was to set the NameTransform object property of the ZipFile to a ZipNameTransform with its TrimPrefix set to the directory of the file. This causes the directory part of the entry names, which are full file paths, to be removed.

public static void ZipFolderContents(string folderPath, string zipFilePath)
{
    string[] files = Directory.GetFiles(folderPath);
    using (ZipFile zipFile = ZipFile.Create(zipFilePath))
    {
        zipFile.NameTransform = new ZipNameTransform(folderPath);
        foreach (string file in files)
        {
            zipFile.BeginUpdate();
            zipFile.Add(file);
            zipFile.CommitUpdate();
        }
    }
}

What's cool is the the NameTransform property is of type INameTransform, allowing customisation of the name transforms.

like image 106
ProfK Avatar answered Sep 27 '22 22:09

ProfK


How about using System.IO.Path.GetFileName() combined with the entryName parameter of ZipFile.Add()?

string[] files = Directory.GetFiles(folderPath);
using (ZipFile zipFile = ZipFile.Create(zipFilePath))
{
     zipFile.BeginUpdate();
     foreach (string file in files)
     {
          zipFile.Add(file, System.IO.Path.GetFileName(file));
     }
     zipFile.CommitUpdate();
}
like image 20
Tamas Czinege Avatar answered Sep 27 '22 20:09

Tamas Czinege