【问题标题】:Streamreader reading the same line multiple times C#Streamreader 多次读取同一行 C#
【发布时间】:2019-09-07 14:58:55
【问题描述】:

我的旧方法(通常是错误的除外)需要很长时间才能从文件中获取多行,然后将参数存储到字典中。 本质上它是打开的文件,一次抓取每隔一行,修改该行然后存储数据(行 pos 和行的第一个元素(减号)“>”)关闭文件,然后重复。

for (int i = 0; i < linecount - 1; i += 2)
{
    string currentline = File.ReadLines 
    (datafile).Skip(i).Take(1).First();
    string[] splitline = currentline.Split(' ');
    string filenumber = splitline[0].Trim('>');
}   for (int i = 0; i < linecount - 1; i += 2)

【问题讨论】:

  • An item with the same key has already been added. datanumber 发生时的确切值是多少?您是否考虑过使用[] 而不是Add
  • File.ReadLines(dataFile).Count() 读取整个文件只是为了获得行数。您真的需要在阅读之前知道多少行吗?您的新实现似乎没有。删除该行应该为初学者节省一些时间。
  • @madreflection 同意,这是旧代码,谢谢指出。
  • while 的最后一行应该是line = sr.ReadLine();。否则你只看第一行。
  • @mjwills 解决了它,谢谢。如果您将其作为答案提交,我会将其标记为已解决。

标签: c# readfile streamreader


【解决方案1】:

您需要在while循环中读取下一行,否则循环体将始终分析第一行(这就是为什么会有Dictionary错误)并且永远不会存在:

while (line != null)
{
    // your current code here
    line = sr.ReadLine();
}

【讨论】:

    【解决方案2】:

    问题是您只读取了文件的第一行。要解决这个问题,您需要确保在循环的每次迭代中调用sr.ReadLine()。这看起来像:

    using (StreamReader sr = File.OpenText(datafile))
    {
        string line = sr.ReadLine();
        while (line != null)
        {
            count = count ++;
            if (count % 2 == 0)
            {
                string[] splitline = line.Split(' ');
                string datanumber = splitline[0].Trim('>');
                index.Add(datanumber, count);
            }
    
            line = sr.ReadLine();
        }
    }
    

    这意味着在每次迭代中,line 的值将是一个新值(来自文件的下一行)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多