How to run R script from C# code?

Viewed 3720

I am using MS Visual Studio R Tools where I can prepare and test script in R language. Then I want to start process (using Process.Start(startInfo)) from C# code to execute this script, wait until it finishes and check output. The script produces some statistical computations and saves results on hard drive in .csv file.

How do I find the path to R interpreter? Is the code below correct?

Is it possible to add command line arguments to the R script when calling it from C# code?

ProcessStartInfo startInfo = new ProcessStartInfo();
r_interpreter_path="???";
startInfo.FileName = r_interpreter_path;
startInfo.Arguments = "\"" + r_script_name + " \"";
//Add command line arguments
startInfo.Arguments += " -sd " + date_start_str + " -ed " + date_end_str;
startInfo.UseShellExecute = false;
startInfo.RedirectStandardOutput = true;
startInfo.CreateNoWindow = true;
startInfo.RedirectStandardError = true;
using (Process process = Process.Start(startInfo))
{
    using (StreamReader reader = process.StandardOutput)
    {
        string result = reader.ReadToEnd();
        Debug.WriteLine(result);
    }
    process.WaitForExit();
    //string errMsg = process.StandardError.ReadToEnd();
    //if (errMsg != "")
    //    return false;
    GC.Collect();
}
1 Answers
Related