C#运行外部控制台应用程序,且无输出?

C#运行外部控制台应用程序,且无输出?,c#,C#,在我的项目(MVC 3)中,我希望使用以下代码运行外部控制台应用程序: string returnvalue = string.Empty; ProcessStartInfo info = new ProcessStartInfo("C:\\someapp.exe"); info.UseShellExecute = false; info.Arguments = "some params"; info.RedirectStandardInput = true;

在我的项目(MVC 3)中,我希望使用以下代码运行外部控制台应用程序:

   string returnvalue = string.Empty;

   ProcessStartInfo info = new ProcessStartInfo("C:\\someapp.exe");
   info.UseShellExecute = false;
   info.Arguments = "some params";
   info.RedirectStandardInput = true;
   info.RedirectStandardOutput = true;
   info.CreateNoWindow = true;

   using (Process process = Process.Start(info))
   {
      StreamReader sr = process.StandardOutput;
      returnvalue = sr.ReadToEnd();
   }

但是我在
returnvalue
中得到一个空字符串,该程序创建了一个文件,但没有创建任何文件。可能没有执行taht
进程

您必须等待外部程序完成,否则您想要读取的输出在您想要读取时甚至不会生成

using (Process process = Process.Start(info))
{
  if(process.WaitForExit(myTimeOutInMilliseconds))
  {
  StreamReader sr = process.StandardOutput;
  returnvalue = sr.ReadToEnd();
  }
}

正如TimothyP在评论中所说,在设置
RedirectStandardError=true
后,然后通过
process.StandardError.ReadToEnd()
我得到错误消息内容

如果我回忆正确,要同时读取标准错误和标准输出,必须使用异步回调:

var outputText = new StringBuilder();
var errorText = new StringBuilder();
string returnvalue;

using (var process = Process.Start(new ProcessStartInfo(
    "C:\\someapp.exe",
    "some params")
    {
        CreateNoWindow = true,
        ErrorDialog = false,
        RedirectStandardError = true,
        RedirectStandardOutput = true,
        UseShellExecute = false
    }))
{
    process.OutputDataReceived += (sendingProcess, outLine) =>
        outputText.AppendLine(outLine.Data);

    process.ErrorDataReceived += (sendingProcess, errorLine) =>
        errorText.AppendLine(errorLine.Data);

    process.BeginOutputReadLine();
    process.BeginErrorReadLine();
    process.WaitForExit();
    returnvalue = outputText.ToString() + Environment.NewLine + errorText.ToString();
}

可能是由于标准错误导致的吗?您的IIS apppool用户是否有足够的权限?信息不足。这里没有创建文件,您的问题也不清楚。如果您这样做,请注意,您的站点将无法在中等信任环境下工作,因此您将无法托管大多数共享托管环境公司。@Tony->RedirectStandardError=true,然后var errorReader=process.StandardError->读取,您可能会从applicationprocess.WaitForExit()中获得错误输出。这是一个无效函数,而不是bool