Console.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();

傳回

輸入資料流的下一行字元,或 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;
    }
}

備註

方法 ReadLine 會從標準輸入資料流程讀取一行。 (如需行的定義,請參閱下列 list.) 後面的段落這表示:

  • 如果標準輸入設備是鍵盤,方法 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...
    
  • 如果標準輸入重新導向至檔案,方法 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:
    //       ---
    

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

    ReadLine1 < ReadLine1.txt
    

行定義為字元序列,後面接著歸位字元 (十六進位0x000d) 、換行字元 (十六進位0x000a) 或 屬性的值 Environment.NewLine 。 傳回的字串不包含終止字元 (s) 。 根據預設,方法會從 256 個字元的輸入緩衝區讀取輸入。 因為這包括 Environment.NewLine 字元 () ,所以 方法可以讀取最多包含 254 個字元的行。 若要讀取較長的 OpenStandardInput(Int32) 行,請呼叫 方法。

方法 ReadLine 會以同步方式執行。 也就是說,它會封鎖直到讀取一行或 按下 Ctrl+Z 鍵盤組合 (接著 Windows) 的 Enter 。 屬性會 InTextReader 回 物件,表示標準輸入資料流程,而且同時具有同步 TextReader.ReadLine 方法和非同步 TextReader.ReadLineAsync 方法。 不過,當做主控台的標準輸入資料流程使用時,會 TextReader.ReadLineAsync 以同步方式執行,而不是以非同步方式執行,而且只有在讀取作業完成之後才會傳 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
//
//       >

適用於

產品 版本
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9, 10
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.3, 1.4, 1.6, 2.0, 2.1

另請參閱