I want to run an r script in vb.net which saves data in a .csv file. Till now i found the following approaches:
dim strCmd as String
strCmd = \"R CMD BATCH\"
Here is the class I recently wrote for this purpose. You can also pass in and return arguments from C# and R:
/// <summary>
/// This class runs R code from a file using the console.
/// </summary>
public class RScriptRunner
{
/// <summary>
/// Runs an R script from a file using Rscript.exe.
/// Example:
/// RScriptRunner.RunFromCmd(curDirectory + @"\ImageClustering.r", "rscript.exe", curDirectory.Replace('\\','/'));
/// Getting args passed from C# using R:
/// args = commandArgs(trailingOnly = TRUE)
/// print(args[1]);
/// </summary>
/// <param name="rCodeFilePath">File where your R code is located.</param>
/// <param name="rScriptExecutablePath">Usually only requires "rscript.exe"</param>
/// <param name="args">Multiple R args can be seperated by spaces.</param>
/// <returns>Returns a string with the R responses.</returns>
public static string RunFromCmd(string rCodeFilePath, string rScriptExecutablePath, string args)
{
string file = rCodeFilePath;
string result = string.Empty;
try
{
var info = new ProcessStartInfo();
info.FileName = rScriptExecutablePath;
info.WorkingDirectory = Path.GetDirectoryName(rScriptExecutablePath);
info.Arguments = rCodeFilePath + " " + args;
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();
proc.Close();
}
return result;
}
catch (Exception ex)
{
throw new Exception("R Script failed: " + result, ex);
}
}
}
this is how it works for me:
Dim myprocess As New Process
myprocess.StartInfo = New ProcessStartInfo("C:\Program Files (x86)\R\R-2.6.2\bin\R.exe", "CMD BATCH C:/Users/test/test3.R C:/Users/test/testout.csv")
myprocess.Start()
second approach (first app. doesnt give me a good csv output so here this is a workaround):
Dim proc = New Process
proc.StartInfo.FileName = "C:\Program Files (x86)\R\R-2.6.2\bin\Rscript.exe"
proc.StartInfo.WorkingDirectory = "C:\Program Files (x86)\R\R-2.6.2\bin"
proc.StartInfo.Arguments = "C:/Users/Desktop/RtoVB/test4.r"
proc.StartInfo.UseShellExecute = True
proc.StartInfo.RedirectStandardOutput = False
proc.Start()