Hello! I have a plain text file in which each new element is a new line. Sample file:

Игра Строитель Лампа Стол 

And here I need to load this all into a listBox so that each line in the file is a separate line in listBox. When I do this:

 using (StreamReader sr = new StreamReader(File.Open("history.txt", FileMode.Open))) { listHistory.Items.Add(sr.ReadToEnd()); } 

I have everything in one line.

    3 answers 3

    If "every new item is a new line", i.e. the file looks like this:

     Игра Строитель Лампа Стол 

    then you can solve it like this:

     using (StreamReader sr = new StreamReader(File.Open("history.txt", FileMode.Open))) { while (!sr.EndOfStream) listHistory.Items.Add(sr.ReadLine()); } 
    • Thank you, that's what helped (second version) - Angus123

    StreamReader.ReadToEnd () reads to the end of the file in one line. Use StreamReader.ReadLine ().

      There is one drawback to the option

       using (StreamReader sr = new StreamReader(File.Open("history.txt", FileMode.Open))) { while (!sr.EndOfStream) listHistory.Items.Add(sr.ReadLine()); } 

      We have to call the file many times. And this is quite a long process.
      It is more logical to read the entire sr.ReadToEnd () file;
      And then split the file into parts in the code itself.
      Like that

       string[] strings; using (StreamReader sr = new StreamReader(@"path.txt")) { strings = sr.ReadToEnd().Split(new char[] { '\n' }); } 

      If I'm wrong, I would ask for a fix. The code above is a compressed version of this code.

       string[] strings; using (StreamReader sr = new StreamReader(@"path.txt")) { string s = sr.ReadToEnd(); char[] divizorz = new char[] { '\n' }; strings = s.Split(divizorz); } 

      Just in my opinion the top is better, because the code is not cluttered with unnecessary names
      Here \ n it means a newline character