Search code examples
c#dotnetzip

DotNetZip Creates Subfolders Containing the File Paths


I .zip a file using DotNetZip, but inside contains subfolders of the actual filepath.

Example: Open Zip > (Users) folder > (Admin) folder > (Desktop) folder > file1.csv

May I know where I should change to that the .zip only contains the file itself?

using (ZipFile zip = new ZipFile())
{
    zip.Password = "password";
    zip.AddFile("C:\\Users\\Admin\\Desktop\\File1.csv");
    zip.Save("Encrypted_File1.zip");
}

I am unsure how to change the .AddFile statement as there is no declaration of file path anywhere else.


Solution

  • Based on the documentation, I believe you need to write it like this:

    using (ZipFile zip = new ZipFile())
    {
        zip.Password = "password";
        zip.AddFile("C:\\Users\\Admin\\Desktop\\File1.csv", "Admin\\Desktop\\File1.csv");
        zip.Save("Encrypted_File1.zip");
    }
    

    P.S. If you're doing many files and you have a common base path, you could use something like Path.GetRelativePath to get the in-zip path:

    using (ZipFile zip = new ZipFile())
    {
        string commonBasePath = "C:\\Users";
    
        // for each file
        string filePath = "C:\\Users\\Admin\\Desktop\\File1.csv";
        string inZipPath = Path.GetRelativePath(commonBasePath, filePath);
        zip.Password = "password";
        zip.AddFile(filePath, inZipPath);
        // done
    
        // save
        zip.Save("Encrypted_File1.zip");
    }