使用C#进行压缩

4
我正在尝试使用C#中的GZipStream创建一个gz文件。我的问题是我有一个包含字符串的列表,并且我需要创建一个密码保护的zip文件,其中包含一个包含这些字符串的文本文件。
我不想先创建文本文件,然后将其压缩,最后再删除文本文件。我希望直接创建一个包含文本文件的密码保护的zip文件。
有什么帮助吗?
编辑:我已经完成了压缩工作。现在我需要为创建的zip文件设置密码。有什么帮助吗?

1
顺便提一下,GZipStream 不会创建 .zip 文件,它创建的是 .gz 文件。我现在假设这就是你想要的;如果不是,请相应地更正问题。 - Pavel Minaev
@scatman:如果这个问题已经得到了答案,请标记您接受的答案。如果您有不同的问题,请使用“提问”按钮开始一个新的问题。谢谢。 - NotMe
@scatman - Sharpziplib 支持密码。 - Keltex
3个回答

3

只需创建一个包装GZipStreamStreamWriter,并向其中写入文本。


3
你应该考虑使用SharpZipLib。它是一个开源的.NET压缩库。它包括创建.gz.zip文件的示例。请注意,您可以直接写入.zip文件,无需先在磁盘上创建中间文件。
编辑:(回应您的编辑)SharpZipLib还支持zip密码。

同意……这个库很好用,而且很适合.NET编程风格。 - harpo

0

GZipStream可以用于创建.gz文件,但这与.zip文件不同。

如果要创建受密码保护的zip文件,我认为您需要使用第三方库。

以下是使用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");
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接