Search code examples
c#cmdkeystore

Executing Command line .exe with parameters in C#


I'm trying to execute a command line program with parameters from C#. I would have imagined that standing this up and making this happen would be trivial in C# but its proving challenging even with all the resources available on the this site and beyond. I'm at a loss so I will provide as much detail as possible.

My current approach and code is below and in the debugger the variable command has the following value.

command = "C:\\Folder1\\Interfaces\\Folder2\\Common\\JREbin\\keytool.exe -import -noprompt -trustcacerts -alias myserver.us.goodstuff.world -file C:\\SSL_CERT.cer -storepass changeit -keystore keystore.jks"

The problem may be how I am calling and formatting the string I use in that variable command.

Any thoughts on what might be the issue?

ProcessStartInfo procStartInfo = new ProcessStartInfo("cmd", "/c " + command);

    procStartInfo.RedirectStandardOutput = true;
    procStartInfo.UseShellExecute = false;
    procStartInfo.CreateNoWindow = true;
    Process process = new Process();
    process.StartInfo = procStartInfo;
    process.Start();
    string result = process.StandardOutput.ReadToEnd();
    Console.WriteLine(result);

I get back no information or error in the variable result once its completes.


Solution

  • Wait for the process to end (let it do its work):

    ProcessStartInfo procStartInfo = new ProcessStartInfo("cmd", "/c " + command);
    
    procStartInfo.RedirectStandardOutput = true;
    procStartInfo.UseShellExecute = false;
    procStartInfo.CreateNoWindow = true;
    
    // wrap IDisposable into using (in order to release hProcess) 
    using(Process process = new Process()) {
      process.StartInfo = procStartInfo;
      process.Start();
    
      // Add this: wait until process does its work
      process.WaitForExit();
    
      // and only then read the result
      string result = process.StandardOutput.ReadToEnd();
      Console.WriteLine(result);
    }