2017-04-11 72 views
0

所以我試圖顯示我的數據從使用部分之外的StreamReader。我能夠將它顯示在StreamReader的所有INSIDE中,但是將其顯示在StreamReader的外部會變得更加複雜。如何通過StreamReader外部的循環顯示我的數據

我明白我的StreamReader內部的while循環將顯示我需要的所有數據(它是)。但我需要它從底部的循環中展示出來。 (while循環僅作爲參考)。

當我運行它通過for循環我要麼得到 「結束 結束 結束 結束」 或 「結束 記錄 指標 」

我得到的「結束」當我使用for循環中的數組索引號,以及當我使用「i」時的「記錄指示符結束」。

我怎樣才能讓它顯示我的while循環顯示什麼?

class Program 
{ 
    static void Main(string[] args) 
    { 
     string[] lineOutVar; 
      using (StreamReader readerOne = new StreamReader("../../FileIOExtraFiles/DataFieldsLayout.txt")) 
      { 
       string lineReader = readerOne.ReadLine(); 
       string[] lineOutput = lineReader.Split('\n'); 
      lineOutVar = lineOutput; 



      while (readerOne.EndOfStream == false) 
      { 
       lineOutVar = readerOne.ReadLine().Split(); 
       Console.WriteLine(lineOutVar[0]); 
      } 

     } 
     for (int i = 0; i < lineOutVar.Length; i++) 
     { 
      Console.WriteLine(lineOutVar[0]); 
     } 
+0

將其捕獲到一個變量中,以便在流關閉後可以使用它。 –

+0

這就是lineOutVar的用途。我在StreamReader開始之前調用它,將它放入StreamReader中並使其等於我的lineOutPut var,然後在StreamReader外調用它。但由於某些原因,只給了我4個數據索引。除非我誤解你的說法。 – Popplars

+0

數組可能不是正確的容器,因爲它的大小需要提前聲明。看起來你只是反覆地將它分配給一個分割線,而不是將每一行分配給數組中的唯一索引。你可能會考慮一個列表。也看看'File.ReadAllLines'而不是'StreamReader'的東西。 –

回答

0

使用List類。

List<string> lineOutVar = new List<string>(); 
    using (System.IO.StreamReader readerOne = new System.IO.StreamReader("../../FileIOExtraFiles/DataFieldsLayout.txt")) 
    { 
     while(readerOne.EndOfStream == false) 
     { 
      string lineReader = readerOne.ReadLine(); 
      lineOutVar.Add(lineReader); //add the line to the list of string 
     } 
    } 

    foreach(string line in lineOutVar) //loop through each of the line in the list of string 
    { 
     Console.WriteLine(line); 
    } 
0

獲取內容:

string[] lineOutVar; 
List<string[]> lst_lineOutVar = new List<string[]>(); 
using (StreamReader readerOne = new StreamReader("E:\\TEST\\sample.txt")) 
{ 
     string lineReader = readerOne.ReadLine(); 
     string[] lineOutput = lineReader.Split('\n'); 
     lineOutVar = lineOutput; 



     while (readerOne.EndOfStream == false) 
     { 
        lineOutVar = new string[1]; 
        lineOutVar = readerOne.ReadLine().Split(); 

        lst_lineOutVar.Add(lineOutVar); 

        //Console.WriteLine(lineOutVar[0]); 
       } 

       String getcontent = string.Empty; 
       foreach (var getLst in lst_lineOutVar) 
       { 
        getcontent = getcontent + "," + getLst[0].ToString(); 
       } 


       Console.WriteLine(getcontent); 

      } 
0

你也可以只跳過的StreamReader和使用File.ReadAllLines

string[] lineOutVar = File.ReadAllLines("../../FileIOExtraFiles/DataFieldsLayout.txt"); 

現在你有文件行的數組,你可以循環它們並將它們分開,不過你喜歡。