27

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?

Jean Carlos
  • 1,613
  • 3
  • 18
  • 26
  • assume path is C:\folder1\folder2\file1.txt which folder do you want to zip and lock with password? – Amey Kamat Oct 18 '16 at 18:46
  • 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. – Jean Carlos Oct 18 '16 at 18:49

1 Answers1

42

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);
}
petelids
  • 12,305
  • 3
  • 47
  • 57
  • Thank you, the solution is good. But how can we hide the file names while encription? – Habip Oğuz Jul 26 '19 at 05:31
  • @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. – petelids Jul 26 '19 at 10:59
  • @petelids, Hımm, thank you very much. That time, I will search a purchased one like WinRar. – Habip Oğuz Jul 26 '19 at 14:20
  • @HabipOğuz - I believe 7zip can do what you want. – petelids Jul 26 '19 at 15:30