Setting a password for a zip file

Viewed 4356

I'm trying to set a password for a zip file using SharpZipLib library with .Net Core.

I have followed this example in order to set a password, however once the zip file has been created, the files are in there and the zip file is create, however there is no password.

// Create a password for the Zipfolder
// https://github.com/icsharpcode/SharpZipLib/wiki/Zip-Samples
using (ICSharpCode.SharpZipLib.Zip.ZipFile ZipFile = new ICSharpCode.SharpZipLib.Zip.ZipFile(Path.GetFileName(destinationPath)))
{
     ZipFile.Password = "foo";
     ZipFile.Add(destinationPath, "");
}
3 Answers

None of the above answers worked for me,
With that being said I found this Fast Zip class within the SharpZipLib library that has worked for me.

// Create a password for the Zipfolder
// https://github.com/icsharpcode/SharpZipLib/wiki
ICSharpCode.SharpZipLib.Zip.FastZip zipFile = new ICSharpCode.SharpZipLib.Zip.FastZip();
zipFile.Password = "foo";
zipFile.CreateEmptyDirectories = true;
zipFile.CreateZip(destinationPath,tempPath, true, "");

The only thing I don't like about it however is that is doesn't implement IDisposable

I used the Example from the wiki and it worked without a Problem.

Code:

using (FileStream fsOut = File.Create(@"d:\temp\sharplib_pwtest.zip"))
using (ZipOutputStream zipStream = new ZipOutputStream(fsOut)) {
    zipStream.SetLevel(3);
    zipStream.Password = "Testpassword";
    var folderName = @"D:\temp\sharpZipLibTest\";
    int folderOffset = folderName.Length + (folderName.EndsWith("\\") ? 0 : 1);
    CompressFolder(folderName, zipStream, folderOffset);
}

You just need to put BeginUpdate() and CommitUpdate() and that will reflect in your output.

using (ICSharpCode.SharpZipLib.Zip.ZipFile ZipFile = new ICSharpCode.SharpZipLib.Zip.ZipFile(Path.GetFileName(destinationPath)))
{
    ZipFile.BeginUpdate();
    ZipFile.Password = "foo";
    ZipFile.Add(destinationPath, "");
    ZipFile.CommitUpdate();
}
Related