2017-09-04 78 views
-1

目前我的程序只打印文本文件中最後的274行。如何在控制檯上打印整個文本文件(約500行)?如何在控制檯中從文本文件打印更多行?

下面是我的代碼:

using System; 

namespace InsertTextFileSample 
{ 

    class Program 
    { 

    static void Main(string[] args) 
    { 
     // Example #2 
     // Read each line of the file into a string array. Each element 
     // of the array is one line of the file. 
     string TextFile = Console.ReadLine(); 
     string[] lines = System.IO.File.ReadAllLines(@"C:\Users\Firzanah\Downloads\"+TextFile); 

     // Display the file contents by using a foreach loop. 
     System.Console.WriteLine("Contents of nvram.txt = /n"); 
     foreach (string line in lines) 
     { 
      // Use a tab to indent each line of the file. 
      Console.WriteLine("\t" + line); 
     } 

     // Keep the console window open in debug mode. 
     Console.WriteLine("Press any key to exit."); 
     System.Console.ReadKey(); 
    } 
    } 
} 

[編輯]:實測值的溶液這裏:More line in console output of VS2010

+1

它打印所有行。你爲什麼認爲它不?因爲您的控制檯的回滾不夠大,無法顯示全部內容? –

+0

我檢查了控制檯和文本文件中顯示的消息的長度差異。那時我注意到控制檯上只顯示了最後的274行。 如何讓我的回滾顯示全部? – Firzanah

回答

-1

File.ReadAllLines使用讀取線到一個數組一次。嘗試逐行讀取文件:

using System; 

namespace InsertTextFileSample 
{ 
    class Program 
    { 

     static void Main(string[] args) 
     { 
      string TextFile = Console.ReadLine(); 
      string path = @"C:\Users\Firzanah\Downloads\" + TextFile; 
      string line; 
      var fileReader = 
       new System.IO.StreamReader(path); 

      Console.WriteLine("Contents of nvram.txt = /n"); 
      while ((line = fileReader.ReadLine()) != null) 
      { 
       Console.WriteLine("\t" + line); 
      } 

      fileReader.Close(); 
      Console.ReadKey(); 
     } 
    } 
} 
+0

我試過上面的代碼,但它一直給我錯誤: 1)'string'不包含'ReadLine'的定義 2)'string'不包含'Close'的定義 – Firzanah

+0

你可能已經錯過了這裏的東西。我更新了整個代碼並更改了一些名稱。它應該適合你。我測試過了。這裏沒有錯誤。 –

+0

此答案與原始代碼沒有本質區別。兩者都會讀取文件中的每一行,並且都會將每一行打印到控制檯。所以這個答案不以任何方式解決OP的實際問題。真正的答案是他們的控制檯窗口的行緩衝區不足以存儲所有的輸出,因此除了最後的274行之外的所有行都在程序結束時滾動到窗口緩衝區的頂部。這在標有重複的地方解釋過(它甚至不是一個編程問題......它更像是一個PC用戶問題)。 –

相關問題