遇到挑战,可以通过C#Process类向cmd.exe发送命令。
基本上我想调用R.exe,然后在运行一些R函数然后取出结果之前发送几个命令来暂存数据。
但是我无法从一个简单的“dir”statemenet中得到结果:(
Process p = new Process();
ProcessStartInfo info = new ProcessStartInfo();
info.FileName = "cmd.exe";
info.RedirectStandardInput = true;
info.RedirectStandardOutput = true;
info.UseShellExecute = false;
string pathToR = @"C:\Program Files\R\R-3.3.1\bin";
p.StartInfo = info;
p.Start();
List<string> output = new List<string>();
using (StreamWriter sw = p.StandardInput)
{
if (sw.BaseStream.CanWrite)
{
sw.WriteLine("cd " + pathToR);
sw.WriteLine("dir");
while (p.StandardOutput.Peek() > -1)
{
var peekVal = p.StandardOutput.Peek();
output.Add(p.StandardOutput.ReadLine());
}
}
}
foreach (var line in output)
{
Console.WriteLine(line);
}
p.StandardInput.Close();
p.StandardOutput.Close();
p.WaitForExit();
p.Close();
Console.ReadLine();
输出:
Microsoft Windows [Version 10.0.10586]
(c) 2015 Microsoft Corporation. All rights reserved.
c:\users\micah_000\documents\visual studio 2015\Projects\RStagingTestApp\RStagingTestApp\bin\Debug>cd C:\Program Files\R\R-3.3.1\bin
The process tried to write to a nonexistent pipe.
The process tried to write to a nonexistent pipe.
The process tried to write to a nonexistent pipe.
The process tried to write to a nonexistent pipe.
The process tried to write to a nonexistent pipe.
我已经看到了这个结果的几个变种,但我从未见过我的命令有任何反应:(
答案 0 :(得分:0)
很多地方都说异步读取效果最好。我已经看到了一些有说服力的,全面的解释,但我还没有能够让它为我工作。
This似乎有效。它可能已将AutoFlush设置为true。或者只是在最后阅读一次。