Condividi tramite


Console.ReadLine Metodo

Definizione

Legge la riga di caratteri successiva dal flusso di input standard.

public:
 static System::String ^ ReadLine();
[System.Runtime.Versioning.UnsupportedOSPlatform("android")]
[System.Runtime.Versioning.UnsupportedOSPlatform("browser")]
public static string? ReadLine();
[System.Runtime.Versioning.UnsupportedOSPlatform("browser")]
public static string? ReadLine();
public static string ReadLine();
[<System.Runtime.Versioning.UnsupportedOSPlatform("android")>]
[<System.Runtime.Versioning.UnsupportedOSPlatform("browser")>]
static member ReadLine : unit -> string
[<System.Runtime.Versioning.UnsupportedOSPlatform("browser")>]
static member ReadLine : unit -> string
static member ReadLine : unit -> string
Public Shared Function ReadLine () As String

Restituisce

Riga successiva di caratteri del flusso di input o null se non sono disponibili altre righe.

Attributi

Eccezioni

Si è verificato un errore di I/O.

Memoria insufficiente per allocare un buffer per la stringa restituita.

Il numero di caratteri nella riga successiva di caratteri è maggiore di Int32.MaxValue.

Esempio

L'esempio seguente richiede due argomenti della riga di comando: il nome di un file di testo esistente e il nome di un file in cui scrivere l'output. Apre il file di testo esistente e reindirizza l'input standard dalla tastiera a tale file. Reindirizza anche l'output standard dalla console al file di output. Usa quindi il Console.ReadLine metodo per leggere ogni riga nel file, sostituisce ogni sequenza di quattro spazi con un carattere di tabulazioni e usa il Console.WriteLine metodo per scrivere il risultato nel file di output.

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

Commenti

Il ReadLine metodo legge una riga dal flusso di input standard. Per la definizione di una riga, vedere il paragrafo dopo l'elenco seguente. Ciò significa che:

  • Se il dispositivo di input standard è la tastiera, il ReadLine metodo si blocca fino a quando l'utente non preme il tasto INVIO .

    Uno degli usi più comuni del metodo consiste nel ReadLine sospendere l'esecuzione del programma prima di cancellare la console e visualizzare nuove informazioni oppure chiedere all'utente di premere INVIO prima di terminare l'applicazione. Ciò è illustrato nell'esempio seguente.

    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 l'input standard viene reindirizzato a un file, il ReadLine metodo legge una riga di testo da un file. Ad esempio, di seguito è riportato un file di testo denominato ReadLine1.txt:

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

    Nell'esempio seguente viene usato il ReadLine metodo per leggere l'input reindirizzato da un file. L'operazione di lettura termina quando il metodo restituisce null, che indica che non rimangono righe da leggere.

    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:
    '       ---
    

    Dopo aver compilato l'esempio in un eseguibile denominato ReadLine1.exe, è possibile eseguirlo dalla riga di comando per leggere il contenuto del file e visualizzarli nella console. La sintassi è:

    ReadLine1 < ReadLine1.txt
    

Una riga viene definita come sequenza di caratteri seguita da un ritorno a capo (0x000d esadecimale), da un avanzamento riga (0x000a esadecimale) o dal valore della Environment.NewLine proprietà. La stringa restituita non contiene i caratteri di terminazione. Per impostazione predefinita, il metodo legge l'input da un buffer di input di 256 caratteri. Poiché include i Environment.NewLine caratteri, il metodo può leggere righe contenenti fino a 254 caratteri. Per leggere righe più lunghe, chiamare il OpenStandardInput(Int32) metodo .

Il ReadLine metodo viene eseguito in modo sincrono. Ovvero, si blocca fino a quando non viene letta una riga o la combinazione di tastiera CTRL+Z (seguita da INVIO in Windows), viene premuto. La In proprietà restituisce un TextReader oggetto che rappresenta il flusso di input standard e che ha sia un metodo sincrono TextReader.ReadLine che un metodo asincrono TextReader.ReadLineAsync . Tuttavia, quando viene usato come flusso di input standard della console, viene TextReader.ReadLineAsync eseguito in modo sincrono anziché asincrono e restituisce un solo Task<String> dopo il completamento dell'operazione di lettura.

Se questo metodo genera un'eccezione OutOfMemoryException , la posizione del lettore nell'oggetto sottostante Stream è avanzata dal numero di caratteri che il metodo è stato in grado di leggere, ma i caratteri già letti nel buffer interno ReadLine vengono eliminati. Poiché la posizione del lettore nel flusso non può essere modificata, i caratteri già letti sono irreversibili e possono essere accessibili solo reinizializzando .TextReader Se la posizione iniziale all'interno del flusso è sconosciuta o il flusso non supporta la ricerca, è necessario reinizializzare anche l'oggetto sottostante Stream . Per evitare tale situazione e per produrre codice affidabile, è necessario usare la proprietà e ReadKey il KeyAvailable metodo e archiviare i caratteri di lettura in un buffer preallocato.

Se la combinazione di tasti CTRL+Z (seguita da INVIO in Windows) viene premuta quando il metodo legge l'input dalla console, il metodo restituisce null. In questo modo l'utente può impedire un ulteriore input da tastiera quando il ReadLine metodo viene chiamato in un ciclo. Nel seguente scenario di esempio viene illustrato questo aspetto.

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
'       
'       >

Si applica a

Vedi anche