如何调用ruby脚本并传递一些参数,一旦脚本完成,将控件返回到带有结果的c#代码?
答案 0 :(得分:3)
void runScript()
{
using (Process p = new Process())
{
ProcessStartInfo info = new ProcessStartInfo("ruby C:\rubyscript.rb");
info.Arguments = "args"; // set args
info.RedirectStandardInput = true;
info.RedirectStandardOutput = true;
info.UseShellExecute = false;
p.StartInfo = info;
p.Start();
string output = p.StandardOutput.ReadToEnd();
// process output
}
}
答案 1 :(得分:1)
为了填补较小的空白,我实现了相同的功能,能够异步访问输入流。
public void RunScript(string script, string arguments, out string errorMessage)
{
errorMessage = string.empty;
using (Process process = new Process())
{
process.OutputDataReceived += process_OutputDataReceived;
ProcessStartInfo info = new ProcessStartInfo(script);
info.Arguments = String.Join(" ", arguments);
info.UseShellExecute = false;
info.RedirectStandardError = true;
info.RedirectStandardOutput = true;
info.WindowStyle = ProcessWindowStyle.Hidden;
process.StartInfo = info;
process.EnableRaisingEvents = true;
process.Start();
process.BeginOutputReadLine();
process.WaitForExit();
errorMessage = process.StandardError.ReadToEnd();
}
}
private void process_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
using (AutoResetEvent errorWaitHandle = new AutoResetEvent(false))
{
if (!string.IsNullOrEmpty(e.Data))
{
// Write the output somewhere
}
}
}