📜  C#中的Console.SetIn()方法

📅  最后修改于: 2021-05-29 20:31:09             🧑  作者: Mango

Console.SetIn()方法用于设置指定的StreamReader对象的In属性,即,它将标准输入从控制台重定向到输入文件。由于控制台是使用此StreamReader对象设置的,因此可以调用ReadLine()方法来逐行读取文件的内容。

例外情况:

  • ArgumentNullException:如果newIn为null。
  • SecurityException:如果调用者没有所需的权限。

示例:在此示例中,使用SetIn()方法将StreamReader对象设置为控制台,并且文件的内容将被读取,存储和打印。

使用的文本文件:

// C# program to demonstrate SetIn() method
using System;
using System.IO;
  
class GFG {
  
    // Main Method
    static void Main()
    {
  
        // Create a string to get 
        // data from the file
        string geeks = " ";
  
        // creating the StreamReader object
        // and set it to the desired 
        // text file
        using(StreamReader gfg = new StreamReader("D:\\out.txt"))
        {
  
            // setting the StreamReader 
            // object to the Console
            Console.SetIn(gfg);
  
            string l;
  
            // Reading the contents of the file into l
            while ((l = Console.ReadLine()) != null) 
            {
                geeks = geeks + l;
            }
  
            // Printing the file contents
            // appended to "Hello "
            Console.WriteLine("Hello " + geeks);
  
            // Waiting for user input
            // to exit the program
            Console.ReadKey();
        }
    }
}

输出:

参考:

  • https://docs.microsoft.com/zh-cn/dotnet/api/system.console.setin?view=netframework-4.7.2#System_Console_SetIn_System_IO_TextReader_