4

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?

scatman
  • 14,109
  • 22
  • 70
  • 93
  • 1
    As a side note, `GZipStream` doesn't create .zip files, it creates .gz files. I'll assume that's what you actually want for now; if not, correct the question accordingly. – Pavel Minaev Mar 24 '10 at 18:43
  • @scatman: If this particular question has been answered, please mark the answer that you accepted. If you have a different question, then use the "Ask Question" button to start a new question. Thanks – NotMe Mar 24 '10 at 19:02
  • @scatman - Sharpziplib supports passwords – Keltex Mar 24 '10 at 19:02

3 Answers3

3

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

Pavel Minaev
  • 99,783
  • 25
  • 219
  • 289
3

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
  • 26,220
  • 11
  • 79
  • 111
0

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
  • 189,189
  • 101
  • 473
  • 713