text file: Reading line by line C#

后端 未结 5 426
太阳男子
太阳男子 2021-01-04 19:38

So, let\'s say i have a text file with 20 lines, with on each line different text. i want to be able to have a string that has the first line in it, but when i do NextLine()

5条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-04 20:05

    You can't pass a line number to ReadLine and expect it to find that particular line. If you look at the ReadLine documentation, you'll see it doesn't accept any parameters.

    public override string ReadLine()
    

    When working with files, you must treat them as streams of data. Every time you open the file, you start at the very first byte/character of the file.

    var reader = new StreamReader("c:\\test.txt");      // Starts at byte/character 0
    

    You have to keep the stream open if you want to read more lines.

    using (var reader = new StreamReader("c:\\test.txt"))
    {
        string line1 = reader.ReadLine();
        string line2 = reader.ReadLine();
        string line3 = reader.ReadLine();
        // etc..
    }
    

    If you really want to write a method NextLine, then you need to store the created StreamReader object somewhere and use that every time. Somewhat like this:

    public class MyClass : IDisposable
    {
        StreamReader reader;
    
        public MyClass(string path)
        {
            this.reader = new StreamReader(path);
        }
    
        public string NextLine()
        {
            return this.reader.ReadLine();
        }
    
        public void Dispose()
        {
            reader.Dispose();
        }
    }
    

    But I suggest you either loop through the stream:

    using (var reader = new StreamReader("c:\\test.txt"))
    {
        while (some_condition)
        {
            string line = reader.ReadLine();
            // Do something
        }
    }
    

    Or get all the lines at once using the File class ReadAllLines method:

    string[] lines = System.IO.File.ReadAllLines("c:\\test.txt");
    for (int i = 0; i < lines.Length; i++)
    {
        string line = lines[i];
        // Do something
    }
    

提交回复
热议问题