0

I want cmd command in my c# winforms program. I want use command to compress file with 7zip.

In normal cmd i use cd "C:\Program Files(x86)\7-Zip" & 7z.exe a -tzip "C:\xyz\test\txt" "C:\xyz\test\txt" -m0=BZip2 -mx5

string zip = @"/c C:\Program Files(x86)\7-Zip";
string file = @"/c C:\xyz\txt";
string conv = "/c & 7z.exe a -tzip";
string method = "/c -m0=BZip2 -mx5";

System.Diagnostics.ProcessStartInfo proc = new System.Diagnostics.ProcessStartInfo();

proc.FileName = @"C:\windows\system32\cmd.exe";
proc.Arguments = @"/c cd" + zip + conv + file + file + method;

System.Diagnostics.Process.Start(proc);

Doesn't work my code. How can i use this command in my program. I want compress file when i click in button

Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
Dominik Lorke
  • 31
  • 2
  • 8

2 Answers2

1

Something like this:

// File (exe) to start: combination of folder and exe
string fileName = Path.Combine(
   // Let's not hardcode "C:\Program Files(x86)" and alike
   Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86),
  @"7-Zip", 
  @"7z.exe");

// If desired arguments are
// a -tzip "C:\xyz\test\txt" "C:\xyz\test\txt" -m0=BZip2 -mx5
// we can join them as 
string arguments = string.Join(" ",
  @"a",
  @"-tzip",                //TODO: you may want to have these values
  @"""C:\xyz\test\txt""",  // as variables like file, conv, method etc.
  @"""C:\xyz\test\txt""",
  @"-m0=BZip2",
  @"-mx5");

ProcessStartInfo procInfo = new ProcessStartInfo() {
  FileName  = fileName,   // We want to start fileName
  Arguments = arguments,  // With arguments
}

// Process is IDisposable, do not forget to Dispose HProcess handle
using (var process = Process.Start(procInfo)) {
  // It's fire and forget implementation, if you want to wait for results
  // add process.WaitForExit();
  // process.WaitForExit(); // uncomment, if you want to pause
}
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
0

You seem to have made a mistake with your arguments.

Your current command line will be:

C:\windows\system32\cmd.exe /c cd/c C:\Program Files(x86)\7-Zip/c & 7z.exe a -tzip/c C:\xyz\txt/c C:\xyz\txt/c -m0=BZip2 -mx5

The spurious /c everywhere is not going to help and neither are the lack of spaces.

I'm guessing what you meant to run was these two commands in succession:

cd C:\Program Files(x86)\7-Zip
7z.exe a -tzip C:\xyz\txt C:\xyz\txt -m0=BZip2 -mx5

Which means you should change your code to:

string zip = @" C:\Program Files(x86)\7-Zip";
string file = @" C:\xyz\txt";
string conv = " & 7z.exe a -tzip";
string method = " -m0=BZip2 -mx5";

This will produce:

C:\windows\system32\cmd.exe /c cd C:\Program Files(x86)\7-Zip & 7z.exe a -tzip C:\xyz\txt C:\xyz\txt -m0=BZip2 -mx5
Martin
  • 16,093
  • 1
  • 29
  • 48