4
Reply

Calling R.exe from command prompt using C# not working

TARIQ

TARIQ

Jul 17 2013 4:16 AM
2.6k
Hi

I am facing problem to execute R package via Command prompt using C#.

Following are code snippet:

///Starting Information for process like its path, use system shell i.e. control process by system etc.
  ProcessStartInfo psi = new ProcessStartInfo(@"C:\WINDOWS\system32\cmd.exe");

  // its states that system shell will not be used to control the process instead program will handle the process
  psi.UseShellExecute = false;
  psi.ErrorDialog = false;

  // Do not show command prompt window separately
  psi.CreateNoWindow = true;
  psi.WindowStyle = ProcessWindowStyle.Hidden;

  //redirect all standard inout to program
  psi.RedirectStandardError = true;
  psi.RedirectStandardInput = true;
  psi.RedirectStandardOutput = true;

  //create the process with above infor and start it
  Process plinkProcess = new Process();
  plinkProcess.StartInfo = psi;
  plinkProcess.Start();


//link the streams to standard inout of process
StreamWriter inputWriter = plinkProcess.StandardInput;
StreamReader outputReader = plinkProcess.StandardOutput;
 StreamReader errorReader = plinkProcess.StandardError;

 //send command to cmd prompt and wait for command to execute with thread sleep
 inputWriter.WriteLine("C:"); ---->this command executes
 inputWriter.WriteLine("cd\\");---->this command executes
 inputWriter.WriteLine(@"cd C:\Program Files\R\R-3.0.1\bin\i386");---->this command executes

 inputWriter.WriteLine(@"R.exe"); ---->this command is not working
 inputWriter.WriteLine(@"2+2"); ---->this command is not working
inputWriter.WriteLine(@"mydata <- read.csv('http://www.ats.ucla.edu/stat/data/binary.csv')");---->this command is not working
inputWriter.WriteLine(@"head(mydata)");---->this command is not working


  Thread.Sleep(2000);

// flush the input stream before sending exit command to end process for any unwanted characters
 inputWriter.Flush();
 inputWriter.WriteLine("exit\r\n");

 // read till end the stream into string
 strOutput = outputReader.ReadToEnd();

Console.WriteLine(strOutput);
Console.ReadKey();

Please help what I am doing wrong here.

Thanks,
Tariq Khan

Answers (4)