26

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?

2
  • assume path is C:\folder1\folder2\file1.txt which folder do you want to zip and lock with password?
    – Amey Kamat
    Oct 18, 2016 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. Oct 18, 2016 at 18:49

1 Answer 1

40

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.