tags:

views:

195

answers:

3
+3  Q: 

zipping with c#

hi all, i am trying to use GZipStream to create a gz file using c#. my problem is that i have a list that contains strings. and i need to create a password protected zip file, and put in it a text file containing the strings.
i don't want to create the textfile, then zip it, and then delete the textfile. i want to directly create a password protected zip file that contains the text file.
any help?

EDIT: i am done with the zipping stuff. now i need to set a pass for the created zip file. any help?

+3  A: 

Just create a StreamWriter wrapping your GZipStream, and write text to it.

Pavel Minaev
+3  A: 

You should consider using SharpZipLib. It's an open source .net compression library. It includes examples on how to create either a .gz or a .zip file. Note that you can write directly to the .zip file. You don't need to create an intermediate file on disk first.

Edit: (in response to your edit) SharpZipLib supports zip passwords too.

Keltex
Agreed... this library works well, and fits well into the .NET idiom.
harpo
A: 

GZipStream can be used to create a .gz file, but this is not the same as a .zip file.

For creating password-protected zip files, I think you need to go to a third-party library.

Here's how to do it using DotNetZip...

var sb = new System.Text.StringBuilder();
sb.Append("This is the text file...");
foreach (var item in listOfStrings)
    sb.Append(item);

// sb now contains all the content that will be placed into
// the text file entry inside the zip.

using (var zip = new Ionic.Zip.ZipFile())
{
    // set the password on the zip (implicitly enables encryption)
    zip.Password = "Whatever.You.Like!!"; 
    // optional: select strong encryption
    zip.Encryption = Ionic.Zip.EncryptionAlgorithm.WinZipAes256;
    // add an entry to the zip, specify a name, specify string content
    zip.AddEntry("NameOfFile.txt", sb.ToString());
    // save the file
    zip.Save("MyFile.zip");
}
Cheeso