Console.SetIn() Method in C#

The Console.SetIn() method is used to set the In property of the specified StreamReader object i.e. it redirects the standard input from the console to the input file. Since the console is set with this StreamReader object, the ReadLine() method can be called to read the contents of the file, line by line.

Syntax: public static void SetIn (System.IO.StreamReader newIn);

Parameter:
newIn: It is a stream which is the new standard input.



Exceptions:

  • ArgumentNullException: If the newIn is null.
  • SecurityException: If the caller does not have the required permission.

Example: In this example, the SetIn() method is used to set the StreamReader object to the console, and the file’s content will be read, stored and printed.

Text File Used:

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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();
        }
    }
}

chevron_right


Output:

Reference:



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

1


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.