首页 > 解决方案 > 如何正确格式化带有密码的 ac# 7-zip 字符串?

问题描述

所以我正在用 C# 编写一个加密应用程序,它调用 7zip 将一个文件夹加密到一个 7zip 存档中,并使用之前输入的密码。问题是,由于某种原因,它看到我试图压缩到 7zip 存档中的文件作为 7zip 文件本身,而它实际上只是一个普通文件夹,所以不知道为什么会这样。这是代码:

string sourceName = @"c:\putfilesforencryptionhere";
string targetName = @"c:\encryptedfileshere.7z";
string password = Form2.verify;

// Initialize process information.
ProcessStartInfo p = new ProcessStartInfo();
p.FileName = "C:\\Program Files\\7-Zip\\7zG.exe";

// Use 7-zip
// specify a=archive and -tgzip=gzip
// and then target file in quotes followed by source file in quotes
p.Arguments = "a \"" + targetName + " -p" + password + " " + sourceName;

并且在运行程序时,7zip 会返回此错误:

文件名、目录名或卷标语法不正确。无法打开文件 c:\encryptedfileshere.7z -p09/28/2020 11:17:29 AM c:\putfilesforencryptionhere.7z。

String password = Form2.verify因为它是在以前的表单中输入的密码。我想知道当它是一个普通文件夹时,为什么 7-zip 会将 c:\putfilesforencryptionhere 视为 7zip 文件?

非常感谢。

标签: c#7zip

解决方案


设置 的值时p.Arguments,之前有一个转义引号\"targetName但之后没有。因此,以下字符串的全部内容被解释为存档名称(如错误消息中所示)。

尝试

p.Arguments = "a \"" + targetName + "\" -p" + password + " " + sourceName;

或用于ArgumentList避免转义问题。

p.ArgumentList.Add("a");
p.ArgumentList.Add(targetName);
p.ArgumentList.Add("-p" + password);
p.ArgumentList.Add(sourceName);

推荐阅读