Kuntady Yathish
Kuntady Yathish

Reputation: 49

Run Rscript using ProcessStartInfo from C#

On executing below code I dont get expected value (8) in result variable? Where am I going wrong? Code executes without any error but value of the result variable will be blank throughout

R code:(Script.R)
AddTwo<-function(firstNumber, SecondNumber)
{
Total<-firstNumber+SecondNumber
Total
}

AddTwo(5,3)

I have installed R and RScript.exe present at path given in code

class Program
{
    static void Main(string[] args)
    {
        var rpath = @"C:\Program Files\R\R-3.6.0\bin\Rscript.exe";
        var scriptpath = @"E:\Projects\Cash Forecast\Documents\Payroll\Script.R";
        var output = RunFromCmd(scriptpath, rpath);

        Console.WriteLine(output);
        Console.ReadLine();
    }

    public static string RunFromCmd(string rCodeFilePath, string rScriptExecutablePath)
    {
        string file = rCodeFilePath;
        string result = string.Empty;

        try
        {

             var info = new ProcessStartInfo();
             info.FileName = rScriptExecutablePath;
             info.WorkingDirectory = Path.GetDirectoryName(rScriptExecutablePath);


             info.RedirectStandardInput = false;
             info.RedirectStandardOutput = true;
             info.UseShellExecute = false;
             info.CreateNoWindow = true;

             using (var proc = new Process())
             {
                 proc.StartInfo = info;
                 proc.Start();
                 result = proc.StandardOutput.ReadToEnd();
             }

             return result;
         }
         catch (Exception ex)
         {
             throw new Exception("R Script failed: " + result, ex);
         }
    }
}

Upvotes: 1

Views: 930

Answers (2)

Raushan Rauf
Raushan Rauf

Reputation: 45

Post is old, still sharing the fix as it can help others, during command line execution for R script, if any path is having space then quotes should be added like below

public static string AddQuotesIfRequired(string path)
        {
            return !string.IsNullOrWhiteSpace(path) ?
                path.Contains(" ") && (!path.StartsWith("\"") && !path.EndsWith("\"")) ?
                    "\"" + path + "\"" : path :
                    string.Empty;
        }

Upvotes: 0

Christopher Vickers
Christopher Vickers

Reputation: 1953

I believe you need to wait for the program to run.

proc.WaitForExit();

The program runs but does not have time to get a response before the rest of your C# program continues.

More information can be found here:

https://support.microsoft.com/en-gb/help/305369/how-to-wait-for-a-shelled-application-to-finish-by-using-visual-c

Upvotes: 1

Related Questions