【问题标题】:How do I read in a text file with a loop, line by line [duplicate]如何逐行读取带有循环的文本文件[重复]
【发布时间】:2017-11-19 23:06:46
【问题描述】:

所以我刚刚开始 C#,几乎没有知识,所以这对我来说更多的是学习而不是实际使用。因此,我真正想知道的是,即使有更简单/更快/更智能的解决方案,我如何才能让我的代码按我的方式工作。

所以我想做的是创建一个字符串数组,并使用循环从文本文件的每一行中读取到数组的相应元素中。这就是我在这里尝试做的事情,我很想听听您对此有什么解决方案。

{
    class Program
    {
        static void Main(string[] args)
        {
            StreamReader ki = new StreamReader("kiserlet.txt");
            string[] a = new string[15];
            Console.ReadLine();
            int y = 0;

            int n = 0;
            for (int i = 0; i > 15; i++)
            {
                a[n] = Convert.ToString(ki.ReadLine());
                n++;
            }
            for (int x = 0;x > 15;x++)
            {

                Console.WriteLine(a[y]);
                y++;
            }
            Console.ReadLine();
            ki.Close();
        }
    }
}

【问题讨论】:

  • 为什么数组长度是15?如果正在读取的 txt 超过 15 行怎么办?
  • 你的循环是错误的。您需要 I 符号。
  • 该死的我很笨,非常感谢,立即修复我的代码:)
  • Google 是你的friend
  • 您的 10 个帖子有 11 个答案,但只有一个被接受。接受答案(以及后来点赞的帖子)可以帮助其他用户找到好的帖子,即使您无法发布答案,也是一种可以帮助他人的方式。非常简短的tour 解释了 SO 的工作原理。

标签: c#


【解决方案1】:

您可以将文件的每一行读入一个数组,然后遍历它。

class Program
{
    static void Main(string[] args)
    {
        // this will read all lines from within the File
        // and automatically put them into an array
        //
        var linesRead = File.ReadLines("kiserlet.txt");

        // iterate through each element within the array and
        // print it out
        //
        foreach (var lineRead in linesRead)
        {
            Console.WriteLine(lineRead);
        }
    }
}

【讨论】:

  • 使用ReadLines 可能会更好——尤其是在文件很大的情况下——因为它会延迟返回行。
  • 10k 代表,您没有将其标记为重复? meta.stackexchange.com/questions/10841/…
  • 好答案。但有时我们需要教别人为什么他们的所作所为行不通。在他的例子中,他的循环使用 > 而不是
猜你喜欢
  • 2013-10-04
  • 2012-01-24
  • 1970-01-01
  • 2012-09-05
  • 2015-05-19
  • 2020-02-21
  • 2018-07-02
  • 1970-01-01
  • 2012-11-12
相关资源
最近更新 更多