0

So i have to write a program that reads values (numbers) from Values.txt file and store them into array of integers (at the beginning i dont know the number of values in file so i dont know the length of array). First i loop through the file and use counter variable to get the number of values to store into array. Then comes the problem, i dont know how to start from the beginning of file to catch values and store them into array. When i run it i get 0 0 0 0 0 as a result.

If instead of

myReader.DiscardBufferedData(); 
myReader.BaseStream.Seek(0, SeekOrigin.Begin); 
myReader.BaseStream.Position = 0; 

I use the myReader.Close() and then myReader = new StreamReader("Values.txt), the result is correct, can somebody please explain why this is happening and howcan i fix this code :)

        string lineOfText = "";
        int counter = 0;
        int[] intArray;
        StreamReader myReader = new StreamReader("Values.txt");


        while(lineOfText != null)
        {
            lineOfText = myReader.ReadLine();
            if(lineOfText != null)
            {
                counter++;
            }
        }
        intArray = new int[counter];

        myReader.DiscardBufferedData();
        myReader.BaseStream.Seek(0, SeekOrigin.Begin);
        myReader.BaseStream.Position = 0;

        counter = 0;
        while(lineOfText != null)
        {
            lineOfText = myReader.ReadLine();
            if (lineOfText != null)
            {
                intArray[counter] = int.Parse(lineOfText);
            }
            counter++;
        }
        myReader.Close();

        for (int j = 0; j < intArray.Length; j++)
        {
            Console.WriteLine(intArray[j]);
        }
Ian
  • 30,182
  • 19
  • 69
  • 107
Tandy
  • 31
  • 1
  • 3
  • 1
    _If you can_, you could simplify this quite a bit by simply calling [`File.ReadAllLines()`.](https://msdn.microsoft.com/en-us/library/s2tte0y1(v=vs.110).aspx) – CodingGorilla Mar 21 '16 at 16:14

1 Answers1

2

This explains how to reset the stream if you want to do it in one pass Return StreamReader to Beginning.

Are you required to use an array? A list would be perfect for what your doing, you can then later push that list into an array or just work directly from the list. Code example below:

List<string> ints = new List<string>();
using (StreamReader sr = new StreamReader("example.txt"))
{
    ints.Add(sr.ReadLine());
}
Community
  • 1
  • 1
Cuken
  • 29
  • 3