使用DotNetZip压缩文件

本文关键字:文件 压缩 DotNetZip 使用 | 更新日期: 2023-09-27 18:00:45

我正在尝试压缩和加密用户选择的文件。一切都很好,除了我正在压缩整个路径,即不是文件本身。下面是我的代码,关于如何对所选文件进行压缩和加密的任何帮助。

openFileDialog1.ShowDialog();
var fileName = string.Format(openFileDialog1.FileName);
string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
using (ZipFile zip = new ZipFile())
{
    zip.Password = "test1";
    zip.Encryption = EncryptionAlgorithm.WinZipAes256;
    zip.AddFile(fileName);
    zip.Save(path + "''test.ZIP");
    MessageBox.Show("File Zipped!", "Complete", MessageBoxButtons.OK, MessageBoxIcon.Information);
}

使用DotNetZip压缩文件

您必须为zip存档显式设置文件名:

zip.AddFile(fileName).FileName = System.IO.Path.GetFileName(fileName);

这就是压缩文件并在归档中重命名文件的方法。提取后,将使用新名称创建一个文件。

using (ZipFile zip1 = new ZipFile())
{
   string newName= fileToZip + "-renamed";
   zip1.AddFile(fileToZip).FileName = newName; 
   zip1.Save(archiveName);
}

参考:C#示例