共用方式為


Console.ReadLine 方法

定義

從標準輸入串流讀取下一行字元。

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

傳回

輸入串流中的下一行字元,或 null 若無更多行可用,則為下一行。

屬性

例外狀況

發生了 I/O 錯誤。

記憶體不足以為回傳字串分配緩衝區。

下一行字元的字元數大於 Int32.MaxValue

範例

以下範例需要兩個命令列參數:一個現有文字檔的名稱,以及一個要寫入輸出的檔案名稱。 它會打開現有的文字檔,並將鍵盤上的標準輸入導向該檔案。 它也會將標準輸出從主控台重新導向到輸出檔案。 接著它會用該 Console.ReadLine 方法讀取檔案中的每一行,將每個四個空格的序列替換成一個制表符,並用該 Console.WriteLine 方法將結果寫入輸出檔案。

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

備註

ReadLine 方法從標準輸入串流讀取一行。 (關於直線的定義,請見以下列表後段。)這表示:

  • 若標準輸入裝置為鍵盤, ReadLine 方法會阻塞,直到使用者按下 Enter 鍵。

    ReadLine 方法最常見的用途之一是在清除主控台並顯示新資訊前暫停程式執行,或提示使用者按下 Enter 鍵再終止應用程式。 下列範例說明這點。

    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...
    
  • 如果標準輸入被導向到檔案,該 ReadLine 方法會從檔案讀取一行文字。 例如,以下是一個名為 ReadLine1.txt的文字檔:

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

    以下範例使用 ReadLine 讀取從檔案重定向輸入的方法。 讀取操作在方法返回 null時終止,表示沒有線可讀。

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

    將範例編譯成名為 ReadLine1.exe的可執行檔後,你可以從命令列執行,讀取檔案內容並顯示給主控台。 語法為:

    ReadLine1 < ReadLine1.txt
    

一行定義為一連串字元後接回車(十六進位0x000d)、換行(十六進位0x000a)或屬性值 Environment.NewLine 。 回傳的字串不包含終止字元。 預設情況下,該方法會從 256 字元的輸入緩衝區讀取輸入。 由於包含 Environment.NewLine 字元,該方法可讀取最多包含 254 個字元的行。 要閱讀較長的行數,請呼叫該 OpenStandardInput(Int32) 方法。

ReadLine 方法以同步方式執行。 也就是說,它會阻塞直到讀取一行或按下 Ctrl+Z 鍵盤組合(Windows 上接著 Enter 鍵)為止。 該 In 屬性回傳一個 TextReader 代表標準輸入串流的物件,且同時具備同步 TextReader.ReadLine 方法與非同步 TextReader.ReadLineAsync 方法。 然而,當作為主控台的標準輸入串流時,執行 TextReader.ReadLineAsync 方式是同步而非非同步,且只有在讀取操作完成後才回傳 a Task<String>

若此方法拋 OutOfMemoryException 出例外,讀取器在底層 Stream 物件中的位置會依該方法能讀取的字元數前進,但已讀入內部 ReadLine 緩衝區的字元會被丟棄。 由於讀取器在串流中的位置無法更改,已讀取的字元無法恢復,只能透過重新初始化 來 TextReader存取。 如果串流中的初始位置未知或串流不支援尋道,則底層 Stream 資料也需重新初始化。 為了避免這種情況並產生穩健的程式碼,你應該使用該 KeyAvailable 屬性和 ReadKey 方法,並將讀取字元存入預先分配的緩衝區。

若在讀取主控台輸入時按下 Ctrl+Z 鍵組合(Windows 上接著 Enter ),則該方法會回傳 null。 這讓使用者能在循環中呼叫該方法時,避免進一步輸入 ReadLine 鍵盤。 下列範例會說明此情節。

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

適用於

另請參閱