如何使用Visual C#将命令传递给命令提示符?

时间:2016-06-09 12:39:54

标签: c# winforms command-prompt

我正在创建一个Visual C#应用程序,它在命令提示符中填写正确的参数以检索iTunes Sales和Trends数据。我的目标是将一个字符串传递给命令提示符,但我只能找到正确的目录。以下是我目前的代码。

string argument = (@"c/ java Autoingestion Credentials.properties " + lblVenderID.Text + " " + ddlReportType.Text + " " + ddlDateType.Text + " " + ddlReportSubtype.Text + " " + txtDate.Text);

System.Diagnostics.ProcessStartInfo process = new System.Diagnostics.ProcessStartInfo();
        process.FileName = "cmd.exe";
        process.WorkingDirectory = "C:/iTunes Sales Report/AutoIngestion";
        System.Diagnostics.Debug.WriteLine(argument);
        process.WindowStyle = System.Diagnostics.ProcessWindowStyle.Maximized;
        System.Diagnostics.Process.Start(process);

如图所示,它位于我硬编码的目录中,但它不显示实际运行我希望它运行的命令的文本字符串。 shell

如果有办法在命令行中显示文本,然后按Enter键自动运行命令,这将是很好的。任何反馈都将不胜感激。

1 个答案:

答案 0 :(得分:3)

如果您正在尝试运行cmd并写信给它,那么应该这样做:

var processInfo = new ProcessStartInfo
                    {
                        FileName = "cmd.exe",
                        WorkingDirectory = "C:/iTunes Sales Report/AutoIngestion",
                        RedirectStandardInput = true,
                        RedirectStandardOutput = true,
                        RedirectStandardError = true,
                        UseShellExecute = false,
                        CreateNoWindow = false
                    };

var process = new Process {StartInfo = processInfo };

process.Start();

// This will write your command and excute it
process.StandardInput.WriteLine(argument);

process.WaitForExit();

如果要查看输出,请按以下步骤操作:

string output = string.Empty;
string error = string.Empty;

//If you want to read the Output of that argument
using (StreamReader streamReader = process.StandardOutput)
      {
          output = streamReader.ReadToEnd();
      }

//If you want to read the Error produced by the argument *if any*
using (StreamReader streamReader = process.StandardError)
      {
          error = streamReader.ReadToEnd();
      }