Console.SetIn(TextReader) 方法

定义

In 属性设置为指定的 TextReader 对象。

C#
[System.Runtime.Versioning.UnsupportedOSPlatform("android")]
[System.Runtime.Versioning.UnsupportedOSPlatform("browser")]
[System.Runtime.Versioning.UnsupportedOSPlatform("ios")]
[System.Runtime.Versioning.UnsupportedOSPlatform("tvos")]
public static void SetIn(System.IO.TextReader newIn);
C#
[System.Runtime.Versioning.UnsupportedOSPlatform("browser")]
public static void SetIn(System.IO.TextReader newIn);
C#
public static void SetIn(System.IO.TextReader newIn);

参数

newIn
TextReader

一个流,它是新的标准输入。

属性

例外

newInnull

调用方没有所要求的权限。

示例

下面的示例演示 SetIn 方法的用法。 它用制表符替换字符串中的四个连续空格字符。 若要运行它,必须提供两个命令行参数。 第一个是要将标准输入流重定向到的现有文本文件的名称。 第二个是要将标准输出流重定向到的文件的名称。 此文件不需要存在。 如果它这么做,其内容将被覆盖。

C#
using System;
using System.IO;

public class InsertTabs
{
    private const int tabSize = 4;
    private const string usageText = "Usage: INSERTTABS inputfile.txt outputfile.txt";
    public static int Main(string[] args)
    {
        if (args.Length < 2)
        {
            Console.WriteLine(usageText);
            return 1;
        }

        try
        {
            // Attempt to open output file.
            using (var writer = new StreamWriter(args[1]))
            {
                using (var reader = new StreamReader(args[0]))
                {
                    // Redirect standard output from the console to the output file.
                    Console.SetOut(writer);
                    // Redirect standard input from the console to the input file.
                    Console.SetIn(reader);
                    string line;
                    while ((line = Console.ReadLine()) != null)
                    {
                        string newLine = line.Replace(("").PadRight(tabSize, ' '), "\t");
                        Console.WriteLine(newLine);
                    }
                }
            }
        }
        catch(IOException e)
        {
            TextWriter errorWriter = Console.Error;
            errorWriter.WriteLine(e.Message);
            errorWriter.WriteLine(usageText);
            return 1;
        }

        // Recover the standard output stream so that a
        // completion message can be displayed.
        var standardOutput = new StreamWriter(Console.OpenStandardOutput());
        standardOutput.AutoFlush = true;
        Console.SetOut(standardOutput);
        Console.WriteLine($"INSERTTABS has completed the processing of {args[0]}.");
        return 0;
    }
}

注解

默认情况下, In 属性设置为标准输入流。

StreamReader封装 的 FileStream 可用于从文件接收输入。

适用于

产品 版本
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9, 10
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.3, 1.4, 1.6, 2.0, 2.1

另请参阅