Console.ReadLine Método

Definição

Lê a linha seguinte de caracteres do fluxo de entrada padrão.

public:
 static System::String ^ ReadLine();
public static string ReadLine();
static member ReadLine : unit -> string
Public Shared Function ReadLine () As String

Devoluções

A próxima linha de caracteres do fluxo de entrada, ou null se não houver mais linhas disponíveis.

Exceções

Ocorreu um erro de I/O.

Não há memória suficiente para alocar um buffer para a cadeia devolvida.

O número de caracteres na linha seguinte é superior ao Int32.MaxValue.

Exemplos

O exemplo seguinte requer dois argumentos de linha de comandos: o nome de um ficheiro de texto existente e o nome de um ficheiro para escrever a saída. Abre o ficheiro de texto existente e redireciona a entrada padrão do teclado para esse ficheiro. Também redireciona a saída padrão da consola para o ficheiro de saída. Depois, utiliza o Console.ReadLine método para ler cada linha do ficheiro, substitui cada sequência de quatro espaços por um carácter tab e usa o Console.WriteLine método para escrever o resultado no ficheiro de saída.

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

let tabSize = 4
let usageText = "Usage: INSERTTABS inputfile.txt outputfile.txt"

[<EntryPoint>]
let main args =
    if args.Length < 2 then
        Console.WriteLine usageText
        1
    else
        try
            // Attempt to open output file.
            use reader = new StreamReader(args[0])
            use writer = new StreamWriter(args[1])
            
            // 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
            
            let mutable line = Console.ReadLine()
            while line <> null do
                let newLine = line.Replace(("").PadRight(tabSize, ' '), "\t")
                Console.WriteLine newLine
                line <- Console.ReadLine()

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

        with :? IOException as e -> 
            let errorWriter = Console.Error
            errorWriter.WriteLine e.Message
            errorWriter.WriteLine usageText
            1
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

Observações

O ReadLine método lê uma linha do fluxo de entrada padrão. (Para a definição de linha, veja o parágrafo após a lista seguinte.) Isto significa que:

  • Se o dispositivo de entrada padrão for o teclado, o ReadLine método bloqueia-se até o utilizador pressionar a tecla Enter .

    Um dos usos mais comuns do ReadLine método é pausar a execução do programa antes de limpar a consola e mostrar nova informação, ou pedir ao utilizador que pressione a tecla Enter antes de terminar a aplicação. O seguinte exemplo ilustra precisamente isto.

    using System;
    
    public class Example
    {
       public static void Main()
       {
          Console.Clear();
    
          DateTime dat = DateTime.Now;
    
          Console.WriteLine("\nToday is {0:d} at {0:T}.", dat);
          Console.Write("\nPress any key to continue... ");
          Console.ReadLine();
       }
    }
    // The example displays output like the following:
    //     Today is 10/26/2015 at 12:22:22 PM.
    //
    //     Press any key to continue...
    
    open System
    
    Console.Clear()
    
    let dat = DateTime.Now
    
    printfn $"\nToday is {dat:d} at {dat:T}." 
    printf "\nPress any key to continue... "
    Console.ReadLine() |> ignore
    
    // The example displays output like the following:
    //     Today is 12/28/2021 at 8:23:50 PM.
    //
    //     Press any key to continue...
    
    Module Example
       Public Sub Main()
          Console.Clear()
    
          Dim dat As Date = Date.Now
    
          Console.WriteLine()
          Console.WriteLine("Today is {0:d} at {0:T}.", dat)
          Console.WriteLine()
          Console.Write("Press any key to continue... ")
          Console.ReadLine()
       End Sub
    End Module
    ' The example displays output like the following:
    '     Today is 10/26/2015 at 12:22:22 PM.
    '     
    '     Press any key to continue...
    
  • Se a entrada padrão for redirecionada para um ficheiro, o ReadLine método lê uma linha de texto de um ficheiro. Por exemplo, segue-se um ficheiro de texto chamado ReadLine1.txt:

    
    This is the first line.
    This is the second line.
    This is the third line.
    This is the fourth line.
    
    

    O exemplo seguinte utiliza o ReadLine método para ler a entrada que é redirecionada de um ficheiro. A operação de leitura termina quando o método retorna null, o que indica que não restam linhas por ler.

    using System;
    
    public class Example
    {
       public static void Main()
       {
          if (!Console.IsInputRedirected) {
             Console.WriteLine("This example requires that input be redirected from a file.");
             return;
          }
    
          Console.WriteLine("About to call Console.ReadLine in a loop.");
          Console.WriteLine("----");
          String s;
          int ctr = 0;
          do {
             ctr++;
             s = Console.ReadLine();
             Console.WriteLine("Line {0}: {1}", ctr, s);
          } while (s != null);
          Console.WriteLine("---");
       }
    }
    // The example displays the following output:
    //       About to call Console.ReadLine in a loop.
    //       ----
    //       Line 1: This is the first line.
    //       Line 2: This is the second line.
    //       Line 3: This is the third line.
    //       Line 4: This is the fourth line.
    //       Line 5:
    //       ---
    
    open System
    
    if not Console.IsInputRedirected then
        printfn "This example requires that input be redirected from a file."
    
    printfn "About to call Console.ReadLine in a loop."
    printfn "----"
    
    let mutable s = ""
    let mutable i = 0
    
    while s <> null do
        i <- i + 1
        s <- Console.ReadLine()
        printfn $"Line {i}: {s}"
    printfn "---"
    
    
    // The example displays the following output:
    //       About to call Console.ReadLine in a loop.
    //       ----
    //       Line 1: This is the first line.
    //       Line 2: This is the second line.
    //       Line 3: This is the third line.
    //       Line 4: This is the fourth line.
    //       Line 5:
    //       ---
    
    Module Example
       Public Sub Main()
          If Not Console.IsInputRedirected Then
             Console.WriteLine("This example requires that input be redirected from a file.")
             Exit Sub 
          End If
    
          Console.WriteLine("About to call Console.ReadLine in a loop.")
          Console.WriteLine("----")
          Dim s As String
          Dim ctr As Integer
          Do
             ctr += 1
             s = Console.ReadLine()
             Console.WriteLine("Line {0}: {1}", ctr, s)
          Loop While s IsNot Nothing
          Console.WriteLine("---")
       End Sub
    End Module
    ' The example displays the following output:
    '       About to call Console.ReadLine in a loop.
    '       ----
    '       Line 1: This is the first line.
    '       Line 2: This is the second line.
    '       Line 3: This is the third line.
    '       Line 4: This is the fourth line.
    '       Line 5:
    '       ---
    

    Depois de compilar o exemplo para um executável chamado ReadLine1.exe, pode executá-lo a partir da linha de comandos para ler o conteúdo do ficheiro e exibi-lo na consola. A sintaxe é:

    ReadLine1 < ReadLine1.txt
    

Uma linha é definida como uma sequência de caracteres seguida de um retorno de carro (0x000d hexadecimal), um avanço de linha (0x000a hexadecimal) ou o valor da Environment.NewLine propriedade. A cadeia devolvida não contém o(s) carácter(ões) terminante. Por defeito, o método lê a entrada de um buffer de entrada de 256 caracteres. Como isto inclui o Environment.NewLine (s) caractere(s), o método pode ler linhas que contenham até 254 caracteres. Para ler linhas mais longas, chame o OpenStandardInput(Int32) método.

O ReadLine método executa-se de forma síncrona. Ou seja, bloqueia até que uma linha seja lida ou até que a combinação de teclado Ctrl+Z (seguida de Enter no Windows) seja pressionada. A In propriedade devolve um TextReader objeto que representa o fluxo de entrada padrão e que tem tanto um método síncrono TextReader.ReadLine como um método assíncrono TextReader.ReadLineAsync . No entanto, quando usado como fluxo de entrada padrão da consola, executa-se TextReader.ReadLineAsync de forma síncrona em vez de assíncrona e só retorna um Task<String> após a operação de leitura estar concluída.

Se este método lançar uma OutOfMemoryException exceção, a posição do leitor no objeto subjacente Stream é avançada pelo número de caracteres que o método conseguiu ler, mas os caracteres já lidos no buffer interno ReadLine são descartados. Como a posição do leitor no fluxo não pode ser alterada, os caracteres já lidos são irrecuperáveis e só podem ser acedidos reinicializando o TextReader. Se a posição inicial dentro do fluxo for desconhecida ou este não suportar a procura, o subjacente Stream também precisa de ser reinicializado. Para evitar tal situação e produzir código robusto, deve usar a KeyAvailable propriedade e ReadKey o método e armazenar os caracteres lidos num buffer pré-alocado.

Se a combinação de teclas Ctrl+Z (seguida de Enter no Windows) for pressionada enquanto o método está a ler a entrada da consola, o método devolve null. Isto permite ao utilizador evitar mais entradas do teclado quando o ReadLine método é chamado num loop. O seguinte exemplo ilustra este cenário.

using System;

public class Example
{
   public static void Main()
   {
      string line;
      Console.WriteLine("Enter one or more lines of text (press CTRL+Z to exit):");
      Console.WriteLine();
      do {
         Console.Write("   ");
         line = Console.ReadLine();
         if (line != null)
            Console.WriteLine("      " + line);
      } while (line != null);
   }
}
// The following displays possible output from this example:
//       Enter one or more lines of text (press CTRL+Z to exit):
//
//          This is line #1.
//             This is line #1.
//          This is line #2
//             This is line #2
//          ^Z
//
//       >
open System

printfn "Enter one or more lines of text (press CTRL+Z to exit):\n"

let mutable line = ""

while line <> null do
    printf "   "
    line <- Console.ReadLine()
    if line <> null then
        printfn $"      {line}"


// The following displays possible output from this example:
//       Enter one or more lines of text (press CTRL+Z to exit):
//
//          This is line #1.
//             This is line #1.
//          This is line #2
//             This is line #2
//          ^Z
//
//       >
Module Example
   Public Sub Main()
      Dim line As String
      Console.WriteLine("Enter one or more lines of text (press CTRL+Z to exit):")
      Console.WriteLine()
      Do 
         Console.Write("   ")
         line = Console.ReadLine()
         If line IsNot Nothing Then Console.WriteLine("      " + line)
      Loop While line IsNot Nothing   
   End Sub
End Module
' The following displays possible output from this example:
'       Enter one or more lines of text (press CTRL+Z to exit):
'       
'          This is line #1.
'             This is line #1.
'          This is line #2
'             This is line #2
'          ^Z
'       
'       >

Aplica-se a

Ver também