We are trying to execute an R script from C# for .NET core GET API in visual studio and are not able to return any status from R script (as execution status). Below is what we have tried. Versions - .NET Core 3.1, R 4.2
C# Code:
[HttpGet] public IActionResult RunRScript() { try { var rpath = @"C:\Users\AppData\Local\Programs\R\R-4.2.0\bin\Rscript.exe"; string FilePath = Directory.GetCurrentDirectory() + "\\RScripts\\Sample.R"; var output = RFromCmd(rpath, FilePath, ""); return Ok(output); } catch (Exception e) { return BadRequest(e.Message.ToString()); } } public static string RFromCmd(string rScriptExecutablePath, string rCodeFilePath, string args) { string result = string.Empty; try { var info = new ProcessStartInfo(); info.FileName = rScriptExecutablePath; info.WorkingDirectory = Path.GetDirectoryName(rScriptExecutablePath); info.Arguments = rCodeFilePath; info.RedirectStandardInput = false; info.RedirectStandardOutput = true; info.UseShellExecute = false; info.CreateNoWindow = true; using (var proc = new Process()) { proc.StartInfo = info; proc.Start(); } } }
Sample.R
getwd() #Dummy data sample <- data.frame(Date = seq(as.Date("2000/1/1"), by = "month", length.out = 200), Volume = rnorm(200)) summary(sample) #To save the Data in csv format write.csv(sample, "Sample_data.csv") View(summary(sample)) #Trying to include return statement end_of_script <- function() { x = 1 #also tried string "complete" return(x) } end_of_script()
Please let me know what we are missing or doing wrong. The R script is a test script, based on the success of this we will be running different R Scripts using this method.