📜  C#中的Console.OpenStandardOutput()方法(带示例)

📅  最后修改于: 2021-05-29 18:58:21             🧑  作者: Mango

Console.OpenStandardOutput方法用于获取标准输出流。下面列出了C#中提供的OpenStandardOutput方法的两个重载:

  • OpenStandardOutput()方法
  • OpenStandardOutput(int32)方法

OpenStandardOutput()方法

它用于获取标准输出流。

例子:

// C# program to illustrate the
// Console.OpenStandardOutput()
// method
using System;
class GFG
{
    static void Main(string[] args)
    {
        // use of Console.OpenStandardOutput() method
        // to print the Geeksforgeeks
        // BeginWrite returns an IAsyncResult that represents
        //  the asynchronous write
        // int32 value like 071, 101 represents the 
        // ascii value of Geeksforgeeks
        if (System.Console.OpenStandardOutput().BeginWrite(new byte[] { 071, 101,101, 
            107,115, 102, 111, 114, 103, 101,101, 
            107,115, 0 },0, 
            13, null, null).AsyncWaitHandle.WaitOne()) 
        { 
        }
    }
}

输出:

Geeksforgeeks

OpenStandardOutput(Int32)方法

它用于获取标准输出流,该输出设置为指定的缓冲区大小。

示例:它将字符串的两个连续的空格字符替换为制表字符。

// C# program to illustrate the 
// Console.OpenStandardOutput(int32) method
using System;
using System.IO;
   
public class GFG
{
    // size of tab
    private const int Val1 = 2;
       
    // working string
    private const string Val_Text = "Geeks for Geeks";
   
    // main function
    public static int Main(string[] args)
    {
        // check for the argument
        if (args.Length < 2)
        {
            Console.WriteLine(Val_Text);
            return 1;
        }
   
        try
        {
            // replacing space characters in a string with
            // a tab character
            using (var wrt1 = new StreamWriter(args[1]))
            {
                using (var rdr1 = new StreamReader(args[0]))
                {
                    Console.SetOut(wrt1);
                    Console.SetIn(rdr1);
                    string line;
                    while ((line = Console.ReadLine()) != null)
                    {
                        string newLine = line.Replace(("").PadRight(Val1, ' '), "\t");
                        Console.WriteLine(newLine);
                    }
                }
            }
        }
        catch(IOException e)
        {
            TextWriter errwrt = Console.Error;
            errwrt.WriteLine(e.Message);
            return 1;
        }
          
        // use of OpenStandardOutput() method
        var standardOutput = new StreamWriter(Console.OpenStandardOutput());
        standardOutput.AutoFlush = true;
          
        // set the output
        Console.SetOut(standardOutput);
        Console.WriteLine("OpenStandardOutput Example");
        return 0;
    }
}

输出:

Geeks for Geeks