Process.StandardInput属性

获取用于写入应用程序输入的流。

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

语法
 
 
 
public StreamWriter StandardInput { get; }
 
/** @property */
public StreamWriter get_StandardInput ()

 
public function get StandardInput () : StreamWriter

属性值

StreamWriter,可用于写入应用程序的标准输入流。
异常
 
 
异常类型条件

InvalidOperationException

由于 ProcessStartInfo.RedirectStandardInput 设置为 false,因此尚未定义 StandardInput 流。

备注
 
 

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

Note注意

若要使用 StandardInput,您必须将 ProcessStartInfo.UseShellExecute 设置为 false,并且将 ProcessStartInfo.RedirectStandardInput设置为 true。否则,写入 StandardInput 流时将引发异常。

示例
 
 

下面的示例阐释了如何重定向进程的 StandardInput 流。该示例通过重定向的输入启动 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();
       
      }
   }
}
原文地址:https://www.cnblogs.com/1175429393wljblog/p/5392070.html