C#C
C#4y ago
Grin

✅ Whenever I read from a file, do I need to close the file if I want to read from it again?

I want to read from a file to get the number of names within the file so I can create an array with a correct number of elements. I'm wondering if it's okay for me to not close the file before determining that number of names.
// Open the file and get a StreamReader object.
                inputFile = File.OpenText("D:\\Projects\\Chapter7\\Ch7-BinarySearch\\Ch7-BinarySearch\\Names.txt");

                //getting the total number of names within the file
                while (!inputFile.EndOfStream)
                    index++;

                //do I need to close the file and reopen it to prevent an error in the next while loop here?

                // While we're not at the end of the array and not at the end of the file, Read the file's contents into the array.
 
int counter = 0;
                while (counter < index && !inputFile.EndOfStream)
                {
                    namesArray[counter] = inputFile.ReadLine();
                    counter++;
                }

                // Close the file.
                inputFile.Close();
Was this page helpful?