从txt文件中读取每一行C#

时间:2016-12-14 19:12:26

标签: c# streamreader readline

我想阅读每一行txt文件。而不是每一行,我得到每一行。问题是为什么以及如何对此采取行动。 LIST.TXT: 60001 60002 60003 60004 ..单行中的每个数字,依此类推100行

        StreamReader podz = new StreamReader(@"D:\list.txt");

        string pd="";
        int count=0;

        while ((pd = podz.ReadLine()) != null) 
        {
            Console.WriteLine("\n number: {0}", podz.ReadLine());
            count++;

        }
        Console.WriteLine("\n c {0}", count);
        Console.ReadLine();

3 个答案:

答案 0 :(得分:1)

因为你在每次循环迭代中读取两行:

while ((pd = podz.ReadLine()) != null) // here
{
    Console.WriteLine("\n number: {0}", podz.ReadLine()); // and here
    count++;
}

相反,只需先阅读该行,然后使用pd变量来存储第二行的行:

while ((pd = podz.ReadLine()) != null)
{
    Console.WriteLine("\n number: {0}", pd);
    count++;
}

答案 1 :(得分:1)

我建议使用文件而不是 Streams Readers

   var lines = File
     .ReadLines(@"D:\list.txt");

   int count = 0;

   foreach (var line in lines) {
     Console.WriteLine("\n number: {0}", line);
     count++;
   }

   Console.WriteLine("\n c {0}", count);
   Console.ReadLine();

答案 2 :(得分:1)

您的代码存在一些问题:

  • 您正在错误地读取该行(每次迭代调用ReadLine两次)

  • 您尚未关闭Stream

  • 如果该文件正由另一个进程使用(即写入该文件的进程),则可能会出现一些错误

当文件大小非常大时,StreamReader类非常有用,如果您处理的是小文件,只需拨打System.IO.File.ReadAllLines("FileName")即可。

如果文件大小很大,请遵循此方法

public static List<String> ReadAllLines(String fileName)
{
    using(System.IO.FileStream fs = new System.IO.FileStream(fileName, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read))
    {
        using(System.IO.StreamReader sr = new System.IO.StreamReader(fs))
        {
            List<String> lines = new List<String>();
            while (!sr.EndOfStream)
            {
                lines.Add(sr.ReadLine());
            }
            return lines;
        }
    }
相关问题