【问题标题】:Passing arguments to ProcessStartInfo class将参数传递给 ProcessStartInfo 类
【发布时间】:2012-06-14 20:29:19
【问题描述】:

我想使用 Process.Start 调用命令提示符命令,然后使用 StandardOutput 我想在我的应用程序中使用 StreamReader 进行读取,但是当我运行下面的程序时,在 MessageBox 中我只是找到了 Debug 之前的路径,我的命令我已经在论据中声明不会执行。

ProcessStartInfo info = new ProcessStartInfo("cmd.exe", "net view");
            info.UseShellExecute = false;
            info.CreateNoWindow = true;
            info.RedirectStandardOutput = true;    

            Process proc = new Process();
            proc.StartInfo = info;
            proc.Start();

            using(StreamReader reader = proc.StandardOutput)
            {
                MessageBox.Show(reader.ReadToEnd());
            }

这里我的 net view 命令永远不会执行。

【问题讨论】:

    标签: c# .net processstartinfo redirectstandardoutput


    【解决方案1】:

    如果您想使用cmd 运行命令,您还必须指定/c 参数:

    new ProcessStartInfo("cmd.exe", "/c net view");
    

    但是,在这种情况下,您根本不需要cmdnet 是本机程序,可以按原样执行,无需外壳:

    new ProcessStartInfo("net", "view");
    

    【讨论】:

      【解决方案2】:

      记得截取 StandardErrorOutput 否则什么都看不到:

      var startInfo = new ProcessStartInfo("net", "view");
      startInfo.UseShellExecute = false;
      startInfo.CreateNoWindow = true;
      startInfo.RedirectStandardError = true;
      startInfo.RedirectStandardOutput = true;
      
      using (var process = Process.Start(startInfo))
      {
          string message;
      
          using (var reader = process.StandardOutput)
          {
              message = reader.ReadToEnd();
          }
      
          if (!string.IsNullOrEmpty(message))
          {
              MessageBox.Show(message);
          }
          else
          {
              using (var reader = process.StandardError)
              {
                  MessageBox.Show(reader.ReadToEnd());
              }
          }
      }
      

      【讨论】:

        猜你喜欢
        • 2021-12-31
        • 1970-01-01
        • 1970-01-01
        • 2013-01-08
        • 2022-07-22
        • 1970-01-01
        • 2014-09-09
        相关资源
        最近更新 更多