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]);
}