【问题标题】:how to open the password protectd Zip file in write mode by using the c#?如何使用 c# 以写入模式打开受密码保护的 Zip 文件?
【发布时间】:2023-10-14 10:49:02
【问题描述】:

我已经使用 ionic.zip.dll 使用 zip 保护 csv 文件

看下面的代码

using (ZipFile zip = new ZipFile())
{
   TargetFileName = TargetNamePrefix;
   OutPutDirectoryPath = TargetLocation + "\\" + TargetNamePrefix + ".zip";                  

   zip.Password = zipFilePassword;
   zip.AddFiles(FilePaths, TargetNamePrefix);
   zip.Save(OutPutDirectoryPath)
}

这里的文件路径是字符串[] 变量,它由文件(csv/文本)名称组成。 TargetNamePrefix 表示在 zipfile 文件夹内 Name.OutPutDirectoryPath 表示 使用 zipfileName 输出目录。 那么我如何以写模式打开那些受保护的文件,因为我想将数据写入受保护的 csv 文件。

【问题讨论】:

标签: c# csv zipfile


【解决方案1】:

您可以使用类似的方法提取它们:

using(ZipFile zip = ZipFile.Read(OutPutDirectoryPath))
{
   zip.Password = zipFilePassword; 
   try 
   {
      zip.ExtractAll(TargetLocation);
   }
   catch (BadPasswordException e) 
   {
      // handle error
   }
}  

更新 在不提取的情况下访问单个文件条目到流中

string entry_name = TargetNamePrefix + ".csv"; // update this if needed
using (ZipFile zip = ZipFile.Read(OutPutDirectoryPath))
{
   // Set password for file
   zip.Password = zipFilePassword; 

   // Extract entry into a memory stream
   ZipEntry e = zip[entry_name];
   using(MemoryStream m = new MemoryStream())
   {
      e.Extract(m);
      // Update m stream
   }

   // Remove old entry
   zip.RemoveEntry(entry_name);

   // Add new entry
   zip.AddEntry(entry_name, m);

   // Save
   zip.Save(OutPutDirectoryPath);
}

【讨论】:

  • 对不起...我对提取不感兴趣,因为我想保护数据不受外界影响,只需要以写入模式从 ZIP 文件中打开所需的文件请帮助我破解这个....
  • @Pavan - 查看更新,让我知道这是否适合您。
  • 实际上我需要打开受密码保护的 zip 文件中可用的 csv/txt 文件,我必须使用 SreamWriter 类将数据写入该文件中,请您帮我解决这个问题..
  • 我可以使用 StreamWriter 类打开密码压缩文件吗
  • 在上面的代码中,您删除了现有文件并添加了相同的新文件,但我只需要在现有文件中写入数据。您能帮我解决这个问题吗...