2017-04-11 68 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"); 

现在你有文件行的数组,你可以循环它们并将它们分开,不过你喜欢。