Set password on Zip file using DotNetZip

22,866

Only entries added after the Password property has been set will have the password applied. To protect the directory you are adding, simply set the password before calling AddDirectory.

using (ZipFile zip = new ZipFile())
{
    zip.Password = "password";
    zip.AddDirectory(path);
    zip.Save(outputPath);
}

Note that this is because passwords on Zip files are allocated to the entries within the zip file and not on the zip file themselves. This allows you to have some of your zip file protected and some not:

using (ZipFile zip = new ZipFile())
{
    //this won't be password protected
    zip.AddDirectory(unprotectedPath);
    zip.Password = "password";
    //...but this will be password protected
    zip.AddDirectory(path);
    zip.Save(outputPath);
}
Share:
22,866

Related videos on Youtube

Jean Carlos
Author by

Jean Carlos

Developer and maker.

Updated on July 09, 2022

Comments

  • Jean Carlos
    Jean Carlos almost 2 years

    I'm using DotNetZip to zip my files, but I need to set a password in zip.

    I tryed:

    public void Zip(string path, string outputPath)
        {
            using (ZipFile zip = new ZipFile())
            {
                zip.AddDirectory(path);
                zip.Password = "password";
                zip.Save(outputPath);
            }
        }
    

    But the output zip not have password.

    The parameter pathhas a subfolder for exemple: path = c:\path\ and inside path I have subfolder

    What is wrong?

    • Amey Kamat
      Amey Kamat over 7 years
      assume path is C:\folder1\folder2\file1.txt which folder do you want to zip and lock with password?
    • Jean Carlos
      Jean Carlos over 7 years
      No, the path is a folder and that folder has a subfolder. I want the DotNetZip zip my subfolder and the files inside that. I able to do this, but the password not work. Is the first time I use that lib.
  • Habip Oğuz
    Habip Oğuz almost 5 years
    Thank you, the solution is good. But how can we hide the file names while encription?
  • petelids
    petelids almost 5 years
    @HabipOğuz - I don't think you can. The encryption is on the files and not on the zip container itself. The only way to achieve it that I know of is to double encrypt so if someone were to open the zip archive all they would see is another zip file.
  • Habip Oğuz
    Habip Oğuz almost 5 years
    @petelids, Hımm, thank you very much. That time, I will search a purchased one like WinRar.
  • petelids
    petelids almost 5 years
    @HabipOğuz - I believe 7zip can do what you want.