-2

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.

gymcode
  • 4,431
  • 15
  • 72
  • 128

1 Answers1

1

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");
}
ProgrammingLlama
  • 36,677
  • 7
  • 67
  • 86
  • Hi @John, thank you for your advice. I tried your method of `zip.AddFile`, but the `.zip` file did not appear in the directory. I am doing trial and error on some inputs to see what might work. – gymcode Sep 21 '20 at 01:47
  • If the zip file didn't appear in the directory, I would suspect you're looking in the wrong directory. Anyway, that's outside the scope of this question since you would have had the same problem with your original code. – ProgrammingLlama Sep 21 '20 at 03:44