从c#执行(jar文件)批处理脚本

时间:2012-04-20 08:15:01

标签: c# selenium jar batch-file executable-jar

我有一个包含selenium jar文件的批处理脚本。我想从C#执行批处理脚本。我可以知道它是如何可能的。

example.bat

  

java -jar“selenium jar的路径”

我想从C#执行这个example.bat。

1 个答案:

答案 0 :(得分:1)

使用Process and ProcessStartInfo

command字符串中填写您的java命令或批处理文件名。

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

// The following commands are needed to redirect the standard output.
// This means that it will be redirected to the Process.StandardOutput StreamReader.
procStartInfo.RedirectStandardOutput = true;
procStartInfo.UseShellExecute = false;
// Do not create the black window.
procStartInfo.CreateNoWindow = true;
// Now we create a process, assign its ProcessStartInfo and start it
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo = procStartInfo;
proc.Start();

// Get the output into a string
string result = proc.StandardOutput.ReadToEnd();
// Display the command output.
Console.WriteLine(result);

如果要以异步方式运行它,请尝试使用:

/// <summary>
/// Execute the command Asynchronously.
/// </summary>
/// <param name="command">string command.</param>
public void ExecuteCommandAsync(string command)
{
   try
   {
    //Asynchronously start the Thread to process the Execute command request.
    Thread objThread = new Thread(new ParameterizedThreadStart(ExecuteCommandSync));
    //Make the thread as background thread.
    objThread.IsBackground = true;
    //Set the Priority of the thread.
    objThread.Priority = ThreadPriority.AboveNormal;
    //Start the thread.
    objThread.Start(command);
   }
   catch (ThreadStartException objException)
   {
    // Log the exception
   }
   catch (ThreadAbortException objException)
   {
    // Log the exception
   }
   catch (Exception objException)
   {
    // Log the exception
   }
}