Executing Command line .exe with parameters in C#

前端 未结 3 1706
夕颜
夕颜 2020-12-06 17:49

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 prov

3条回答
  •  死守一世寂寞
    2020-12-06 18:17

    I realized I may have left out some detail that some people may need to solve this in the future.

    Here are the values of the method parameters at run time. I had some confusion as to what the object ProcessStartInfo and Process needed to be stood up correctly I think others may as well.

    exeDir = "C:\folder1\folder2\bin\keytool.exe"

    args = "-delete -noprompt -alias server.us.goodstuff.world -storepass changeit -keystore keystore.jks"

    public bool ExecuteCommand(string exeDir, string args)
    {
      try
      {
        ProcessStartInfo procStartInfo = new ProcessStartInfo();
    
        procStartInfo.FileName = exeDir;
        procStartInfo.Arguments = args;
        procStartInfo.RedirectStandardOutput = true;
        procStartInfo.UseShellExecute = false;
        procStartInfo.CreateNoWindow = true;
    
        using (Process process = new Process())
        {
          process.StartInfo = procStartInfo;
          process.Start();
    
          process.WaitForExit();
    
          string result = process.StandardOutput.ReadToEnd();
          Console.WriteLine(result);
        }
        return true;
      }
      catch (Exception ex)
      {
        Console.WriteLine("*** Error occured executing the following commands.");
        Console.WriteLine(exeDir);
        Console.WriteLine(args);
        Console.WriteLine(ex.Message);
        return false;
      }
    

    Between Dmitry's assistance and the following resource,

    http://www.codeproject.com/Articles/25983/How-to-Execute-a-Command-in-C

    I was able to cobble this together. Thank you!

提交回复
热议问题