C#使用文本文件

时间:2011-10-10 09:23:47

标签: c# visual-studio console-application text-files

我一直在努力工作几个小时,我要完成我正在做的最后一件事。我需要弄清楚如何限制循环从文本行中定义的范围中获取值。像1-5行,然后6-10等

TextReader tr = new StreamReader("values.txt");
        for (int i = 0; i <= 5; i++)
        {
            for (int a = 0; a <= 5; a++)
            {
                line = tr.ReadLine();
                **while ((line = tr.ReadLine()) != null)**
                    for (a = 0; a <= 5; a++){
                        ln = tr.ReadLine();
                        if (ln != null){
                            value = int.Parse(ln);
                            if (value > max)
                                max = value;
                            if (value < min)
                                min = value;}
                    }
                Console.WriteLine(tr.ReadLine());
                if (i % 5 == 0)
                    Console.WriteLine("The max is" + max);
                if (i % 5 == 0)
                    Console.WriteLine("The min is" + min);
                if (i % 5 == 0)
                    Console.WriteLine("-----First 5");
            }

我准备上床但不想睡不着觉。任何正确的推动都会受到赞赏。

2 个答案:

答案 0 :(得分:5)

您可以使用LINQ的Skip docs Take docs 方法轻松实现此目的。只需使用File.ReadAllLines docs 读取您的文字,然后根据需要跳过并拍摄:

var lines = File.ReadAllLines("values.txt").Skip(5).Take(5);
//lines now has lines 6-10

如果您多次这样做,我建议将其拆分为文件访问权限和linq:

var allLines = File.ReadAllLines("values.txt")
var lines6To10 = allLines.Skip(5).Take(5);

... // Later on 

var lines21To25 = allLines.Skip(20).Take(5)

至于你的其余代码..看起来你正试图从行中找到min / max,它应该只包含整数。

var min = int.MaxValue;
var max = int.MinValue;
foreach(var line in lines)
{
   var value = int.Parse(line);
   if(value > max)
      max = value;
   if(value < min)
      min = value;
}

这可以在行示例中看到:http://rextester.com/rundotnet?code=SHP19181(注意加载数字的不同方式,因为rextester无法从文件加载。但原理是相同的)

答案 1 :(得分:0)

如果您想使用StreamReader(例如因为文件大小预计很大),您可以这样做:

using (TextReader tr = new StreamReader("values.txt"))
{
    string currentLine = null;

    do
    {
        Console.WriteLine("processing set of 5 lines");

        for (int i = 0; i < 5; i++)
        {
            currentLine = tr.ReadLine();
            if (currentLine == null)
            {
                break;
            }

            Console.WriteLine("processing line {0} of 5", i);
            // your code goes here:
        }

    } while (currentLine != null);
}

修改:您应该在using block内使用StreamReader(代码已更新)。