Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

calling a ruby script in c#

Tags:

c#

ruby

How do make a call to a ruby script and pass some parameters and once the script is finished return the control back to the c# code with the result?

like image 232
Jony Avatar asked Sep 03 '25 02:09

Jony


2 Answers

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
    }
}
like image 51
Jake Avatar answered Sep 05 '25 19:09

Jake


Just to fill smaller gaps I've implemented the same functionallity with ability to access OutputStream asynchronously.

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
        }
    }
}
like image 27
Bedasso Avatar answered Sep 05 '25 20:09

Bedasso