使用来自C#的ProcessStartInfo运行Rscript

时间:2019-05-14 20:43:04

标签: c# rscript processstartinfo

在执行以下代码时,结果变量中没有得到期望值(8)吗?我要去哪里错了?代码执行时没有任何错误,但是结果变量的值在整个

内都是空白
R code:(Script.R)
AddTwo<-function(firstNumber, SecondNumber)
{
Total<-firstNumber+SecondNumber
Total
}

AddTwo(5,3)

我已经安装了R和RScript.exe,它们位于代码中给出的路径中

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);
         }
    }
}

2 个答案:

答案 0 :(得分:0)

我相信您需要等待程序运行。

proc.WaitForExit();

程序正在运行,但是没有时间在其余C#程序继续之前得到响应。

更多信息可以在这里找到:

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

答案 1 :(得分:0)

Post很旧,仍在共享此修补程序,因为它可以帮助其他人,在R脚本的命令行执行过程中,如果任何路径有空格,则应按如下所示添加引号

println!("{}", (5, 5) > (3, 4)); // true