Process.RedirectStandardInput

时间:2023-03-08 23:33:32
Process.RedirectStandardInput

获取或设置一个值,该值指示应用程序的输入是否从 Process.StandardInput 流中读取。

命名空间:System.Diagnostics
程序集:System(在 system.dll 中)

public bool RedirectStandardInput { get; set; }
/** @property */
public boolean get_RedirectStandardInput () /** @property */
public void set_RedirectStandardInput (boolean value)
public function get RedirectStandardInput () : boolean

public function set RedirectStandardInput (value : boolean)

属性值

若要从 Process.StandardInput 中读取输入,则为 true;否则为 false

Process 可以读取来自它的标准输入流(一般是键盘)的输入文本。通过重定向 StandardInput 流,可以通过编程方式指定进程的输入。例如,可以不使用键盘输入,而从指定文件的内容或另一个应用程序的输出提供文本。

Process.RedirectStandardInput注意

如果要将 RedirectStandardInput 设置为 true,必须先将 UseShellExecute 设置为 false。否则,写入 StandardInput 流时将引发异常。

下面的示例阐释了如何重定向进程的 StandardInput 流。sort 命令是读取文字输入并对其进行排序的一种控制台应用程序。

该示例通过重定向的输入启动 sort 命令。然后它提示用户输入文本,并通过重定向的 StandardInput 流,将用户输入的文本传递给 sort 进程。sort 结果会在控制台上显示给用户。

using System;
using System.IO;
using System.Diagnostics;
using System.ComponentModel; namespace Process_StandardInput_Sample
{
class StandardInputTest
{
static void Main()
{
Console.WriteLine("Ready to sort one or more text lines..."); // Start the Sort.exe process with redirected input.
// Use the sort command to sort the input text.
Process myProcess = new Process(); myProcess.StartInfo.FileName = "Sort.exe";
myProcess.StartInfo.UseShellExecute = false;
myProcess.StartInfo.RedirectStandardInput = true; myProcess.Start(); StreamWriter myStreamWriter = myProcess.StandardInput; // Prompt the user for input text lines to sort.
// Write each line to the StandardInput stream of
// the sort command.
String inputText;
int numLines = 0;
do
{
Console.WriteLine("Enter a line of text (or press the Enter key to stop):"); inputText = Console.ReadLine();
if (inputText.Length > 0)
{
numLines ++;
myStreamWriter.WriteLine(inputText);
}
} while (inputText.Length != 0); // Write a report header to the console.
if (numLines > 0)
{
Console.WriteLine(" {0} sorted text line(s) ", numLines);
Console.WriteLine("------------------------");
}
else
{
Console.WriteLine(" No input was sorted");
} // End the input stream to the sort command.
// When the stream closes, the sort command
// writes the sorted text lines to the
// console.
myStreamWriter.Close(); // Wait for the sort process to write the sorted text lines.
myProcess.WaitForExit();
myProcess.Close(); }
}
}