简体   繁体   English

C#使用StreamReader从文件加载listView子项

[英]C# loading listView subItems from file using StreamReader

I need some help with loading text file into a listView. 我需要一些帮助将文本文件加载到listView中。 Text file looks like this: 文本文件如下所示:

1,6 sec,5 sec,1 sec,17, 1,6秒,5秒,1秒,17,
2,6 sec,4 sec,2 sec,33, 2.6秒,4秒,2秒,33,
3,7 sec,5 sec,3 sec,44, 3,7秒,5秒,3秒,44,

I have to load this into a listView control and every subitem should be separated by comma (or any other character). 我必须将其加载到listView控件中,并且每个子项目都应以逗号(或其他任何字符)分隔。 I tried something like this: 我尝试过这样的事情:

using (var sr = new StreamReader(file))
{
   string fileLine = sr.ReadLine();
   foreach (string piece in fileLine.Split(',')) 
   {     
      listView1.Items.Add(piece); 
   } 
   sr.Close(); 
}

it would work just fine apart from only first line is loaded to the first column in listview. 除了仅将第一行加载到listview的第一列之外,它就可以正常工作。 I cannot figure it out. 我想不明白。

Thanks for your time! 谢谢你的时间! KR! KR!

You have to advance to the next line, you can use a while -loop: 您必须前进到下一行,可以使用while -loop:

using (var sr = new StreamReader(file))
{
    string fileLine;
    while ((fileLine = sr.ReadLine()) != null)
    {
        foreach (string piece in fileLine.Split(','))
        {
            listView1.Items.Add(piece);
        }
    }
}

Note that you don't need to close the stream manually, that is done by the using-statement. 请注意,您不需要手动关闭流,这是通过using语句完成的。

Another way is using File.ReadLines or File.ReadAllLines which can help to simplify your code: 另一种方法是使用File.ReadLinesFile.ReadAllLines ,它们可以帮助简化代码:

var allPieces = File.ReadLines(file).SelectMany(line => line.Split(','));
foreach(string piece in allPieces)
    listView1.Items.Add(piece);

Ι guess you just have to add: 我猜您只需要添加:

while (!sr.EndOfStream)
{
                string fileLine = sr.ReadLine();
                foreach (string piece in fileLine.Split(',')) 
                {     
                        listView1.Items.Add(piece); 
                } 
}

sr.Close();// close put the end of while scope beacause you have a multiline text this code can't be read second line, and throw exceptions this code. sr.Close(); // close由于作用域是多行文本,因此不能在第二行中读取,并在此范围之外结尾,并抛出异常。

using (var sr = new StreamReader(file))
{
     while(!sr.EndOfStream)
     {
          string fileLine = sr.ReadLine();
          foreach (string piece in fileLine.Split(',')) 
          {     
              listView1.Items.Add(piece); 
          } 
          sr.Close(); 
     }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM