Console.SetOut(TextWriter) Console.SetOut(TextWriter) Console.SetOut(TextWriter) Console.SetOut(TextWriter) Method

정의

Out 속성을 TextWriter 개체를 대상으로 설정합니다.Sets the Out property to target the TextWriter object.

public:
 static void SetOut(System::IO::TextWriter ^ newOut);
public static void SetOut (System.IO.TextWriter newOut);
static member SetOut : System.IO.TextWriter -> unit
Public Shared Sub SetOut (newOut As TextWriter)

매개 변수

newOut
TextWriter TextWriter TextWriter TextWriter

새 표준 출력으로 사용할 텍스트 기록기입니다.A text writer to be used as the new standard output.

예외

호출자에게 필요한 권한이 없는 경우The caller does not have the required permission.

예제

다음 예제에서는 SetOut 메서드를 사용하는 방법을 보여 줍니다.The following example illustrates the use of the SetOut method. 탭 문자가 있는 문자열에서 4개의 연속된 공백 문자를 대체합니다.It replaces four consecutive space characters in a string with a tab character. 도구를 실행 하려면 두 명령줄 인수를 제공 해야 합니다.To run it, you must supply two command line arguments. 첫 번째는 표준 입력 스트림을 리디렉션하려는 기존 텍스트 파일의 이름입니다.The first is the name of an existing text file to redirect the standard input stream to. 두 번째는 표준 출력 스트림을 리디렉션하려는 파일의 이름입니다.The second is the name of a file to redirect the standard output stream to. 이 파일이 있을 필요는 없습니다.This file need not exist. 그러한 경우 해당 내용은 덮어씁니다.If it does, its contents will be overwritten.

using namespace System;
using namespace System::IO;

int main()
{
   array<String^>^args = Environment::GetCommandLineArgs();
   const int tabSize = 4;
   String^ usageText = "Usage: INSERTTABS inputfile.txt outputfile.txt";
   StreamWriter^ writer = nullptr;
   if ( args->Length < 3 )
   {
      Console::WriteLine( usageText );
      return 1;
   }

   try
   {
      // Attempt to open output file.
      writer = gcnew StreamWriter( args[ 2 ] );
      // 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( gcnew StreamReader( args[ 1 ] ) );
   }
   catch ( IOException^ e ) 
   {
      TextWriter^ errorWriter = Console::Error;
      errorWriter->WriteLine( e->Message );
      errorWriter->WriteLine( usageText );
      return 1;
   }

   String^ line;
   while ( (line = Console::ReadLine()) != nullptr )
   {
      String^ newLine = line->Replace( ((String^)"")->PadRight( tabSize, ' ' ), "\t" );
      Console::WriteLine( newLine );
   }

   writer->Close();
   
   // Recover the standard output stream so that a 
   // completion message can be displayed.
   StreamWriter^ standardOutput = gcnew StreamWriter( Console::OpenStandardOutput() );
   standardOutput->AutoFlush = true;
   Console::SetOut( standardOutput );
   Console::WriteLine( "INSERTTABS has completed the processing of {0}.", args[ 1 ] );
   return 0;
}

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;
    }
}
Imports System.IO

Public Module InsertTabs
    Private Const tabSize As Integer = 4
    Private Const usageText As String = "Usage: INSERTTABS inputfile.txt outputfile.txt"
   
    Public Function Main(args As String()) As Integer
        If args.Length < 2 Then
            Console.WriteLine(usageText)
            Return 1
        End If
      
        Try
            ' Attempt to open output file.
            Using writer As New StreamWriter(args(1))
                Using reader As 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)
                    Dim line As String = Console.ReadLine()
                    While line IsNot Nothing
                        Dim newLine As String = line.Replace("".PadRight(tabSize, " "c), ControlChars.Tab)
                        Console.WriteLine(newLine)
                        line = Console.ReadLine()
                    End While
                End Using
            End Using
        Catch e As IOException
            Dim errorWriter As TextWriter = Console.Error
            errorWriter.WriteLine(e.Message)
            errorWriter.WriteLine(usageText)
            Return 1
        End Try

        ' Recover the standard output stream so that a 
        ' completion message can be displayed.
        Dim standardOutput As New StreamWriter(Console.OpenStandardOutput())
        standardOutput.AutoFlush = True
        Console.SetOut(standardOutput)
        Console.WriteLine($"INSERTTABS has completed the processing of {args(0)}.")
        Return 0
    End Function 
End Module

설명

기본적으로 Out 속성을 표준 출력 스트림에로 설정 합니다.By default, the Out property is set to the standard output stream.

A StreamWriter 캡슐화 하는 FileStream 파일로 출력을 보내는 데 사용할 수 있습니다.A StreamWriter that encapsulates a FileStream can be used to send output to a file. 예:For example:

Console::WriteLine("Hello World");
FileStream^ fs = gcnew FileStream("Test.txt", FileMode::Create);
// First, save the standard output.
TextWriter^ tmp = Console::Out;
StreamWriter^ sw = gcnew StreamWriter(fs);
Console::SetOut(sw);
Console::WriteLine("Hello file");
Console::SetOut(tmp);
Console::WriteLine("Hello World");
sw->Close();
Console.WriteLine("Hello World");
FileStream fs = new FileStream("Test.txt", FileMode.Create);
// First, save the standard output.
TextWriter tmp = Console.Out;
StreamWriter sw = new StreamWriter(fs);
Console.SetOut(sw);
Console.WriteLine("Hello file");
Console.SetOut(tmp);
Console.WriteLine("Hello World");
sw.Close();
Console.WriteLine("Hello World")
Dim fs As New FileStream("Test.txt", FileMode.Create)
' First, save the standard output.
Dim tmp as TextWriter = Console.Out
Dim sw As New StreamWriter(fs)
Console.SetOut(sw)
Console.WriteLine("Hello file")
Console.SetOut(tmp)
Console.WriteLine("Hello World")
sw.Close()

에서 Out 반환 하는 실제 개체는 제공 된 텍스트 기록기에 대해 동기화 된 래퍼입니다.The actual object returned by Out may be a synchronized wrapper around the provided text writer.

보안

SecurityPermission
비관리 코드를 호출 합니다.for calling unmanaged code. 연결 된 열거형: UnmanagedCodeAssociated enumeration: UnmanagedCode

적용 대상

추가 정보