user14356988
user14356988

Reputation: 19

How to correctly format a c# 7-zip string with a password?

So I am coding an encryption application in C#, which calls on 7zip to encrypt a folder into a 7zip archive with a previous entered password. The trouble is, for some reason it's seeing the file I am trying to compress into the 7zip archive as a 7zip file itself, when it actually is just a normal folder so not sure why that's happening. Here is the code:

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;

And when running the program, 7zip returns this error:

The filename, directory name, or volume label syntax is incorrect. cannot open file c:\encryptedfileshere.7z -p09/28/2020 11:17:29 AM c:\putfilesforencryptionhere.7z.

String password = Form2.verify as it is a password that is entered in a previous form. I wonder why 7-zip would see c:\putfilesforencryptionhere as a 7zip file when it is a normal folder?

Thanks very much.

Upvotes: 1

Views: 1305

Answers (1)

Greg
Greg

Reputation: 23463

When setting the value of p.Arguments, there is an escaped quote \" before targetName but not after. Therefore, the entirety of the following string is being interpreted as the archive name (as seen in the error message).

Try

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

Or use ArgumentList to avoid escaping issues.

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

Upvotes: 2

Related Questions