-1

I need to read the file line by line (each line contains an integer number), parse it from line to number and then, most importantly, ADD ELEMENT to the array!
I leave a piece of code

using (StreamReader sr = new StreamReader (@"input.txt", System.Text.Encoding.Default))
{
    string line;
    while ((line = sr.ReadLine ())! = null) 
    {
        //TODO: Add the element somehow
    }
}

P.S. I apologize in advance for my English). Thanks to all

Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
  • See my answer at following posting : https://stackoverflow.com/questions/7980456/reading-from-a-text-file-in-c-sharp – jdweng Oct 19 '20 at 08:29
  • For the general related: https://stackoverflow.com/questions/32810535/how-to-read-numbers-in-a-txt-file-to-an-integer-array, https://stackoverflow.com/questions/27467321/how-to-read-integers-from-a-text-file-to-array. – Drag and Drop Oct 19 '20 at 08:34
  • Can you give an example of the input.txt file's content and the expected result – VietDD Oct 19 '20 at 08:44

1 Answers1

3

If I understand you right, you can get rid of Stream, but add a simple Linq to File.ReadLines:

using System.IO;
using System.Linq;

... 

int[] result = File
  .ReadLines(@"input.txt")
  .Select(line => int.Parse(line)) 
  .ToArray();

If you want to add records from file to existing array, you can try Concat:

int[] existingData = ...

...

existingData = existingData
  .Concat(File
           .ReadLines(@"input.txt")
           .Select(line => int.Parse(line))) 
  .ToArray(); 
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215