通过c#代码在控制台exe中逐个传递参数

我想用我的c#代码运行一个exe文件。 exe文件是用c#编写的控制台应用程序。

控制台应用程序执行一些操作,包括在数据库中编写内容并将一些文件写入目录。

控制台应用程序(exe文件)需要来自用户的一些输入。 就像它首先问的那样,“你想重置数据库吗?” y表示是,n表示否。 再次,如果用户做出选择,那么应用程序再次询问,“你想重置文件吗?” y表示是,n表示否。 如果用户做出了一些选择,控制台应用程序就会开始执行。

现在我想通过我的c#代码运行这个exe控制台应用程序。 我是这样想的

string strExePath = "exe path"; ProcessStartInfo startInfo = new ProcessStartInfo(); startInfo.CreateNoWindow = false; startInfo.UseShellExecute = false; startInfo.FileName = strExePath; startInfo.WindowStyle = ProcessWindowStyle.Hidden; using (Process exeProcess = Process.Start(startInfo)) { exeProcess.WaitForExit(); } 

我想知道如何通过我的c#代码向控制台应用程序提供用户输入?

请帮我解决这个问题。 提前致谢。

您可以从exe文件重定向输入和输出流。
有关示例,请参阅redirectstandardoutput和redirectstandardinput 。

阅读:

  // Start the child process. Process p = new Process(); // Redirect the output stream of the child process. p.StartInfo.UseShellExecute = false; p.StartInfo.RedirectStandardOutput = true; p.StartInfo.FileName = "Write500Lines.exe"; p.Start(); // Do not wait for the child process to exit before // reading to the end of its redirected stream. // p.WaitForExit(); // Read the output stream first and then wait. string output = p.StandardOutput.ReadToEnd(); p.WaitForExit(); 

写作:

  ... myProcess.StartInfo.RedirectStandardInput = true; myProcess.Start(); StreamWriter myStreamWriter = myProcess.StandardInput; myStreamWriter.WriteLine("y"); ... myStreamWriter.Close(); 

ProcessStartInfo有一个构造函数,您可以将参数传递给:

 public ProcessStartInfo(string fileName, string arguments); 

或者,您可以在它的属性上设置它:

 ProcessStartInfo p = new ProcessStartInfo(); p.Arguments = "some argument"; 

以下是如何将参数传递给* .exe文件的示例:

  Process p = new Process(); // Redirect the error stream of the child process. p.StartInfo.UseShellExecute = false; p.StartInfo.RedirectStandardError = true; p.StartInfo.FileName = @"\filepath.exe"; p.StartInfo.Arguments = "{insert arguments here}"; p.Start(); error += (p.StandardError.ReadToEnd()); p.WaitForExit();