简体   繁体   English

使用DotNetZip压缩文件

[英]Zipping file with DotNetZip

I am trying to zip and encrypt a chosen file from the user. 我正在尝试压缩和加密用户选择的文件。 Everything works fine except that I am zipping the whole path, ie not the file itself. 一切正常,除了我压缩整个路径,即不压缩文件本身。 Below is my code, any help on how I can zip and encrypt on the chosen file. 以下是我的代码,以及有关如何对所选文件进行压缩和加密的任何帮助。

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);
}

您必须为zip归档文件明确设置文件名:

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

This is how you can zip up a file, and rename it within the archive . 这是您可以压缩文件并在存档中重命名的方法。 Upon extraction, a file will be created with the new name. 提取后,将使用新名称创建文件。

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

Reference : C# Examples 参考: C#示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM