I have this code for c# to read all the lines in TestFile.txt but when i finish reading i want to read it again and then put it in a string array (not a List) but when i try do that again it says that the file is already in use. I want to reset the stream or do something like sr.Close() because first time i read it i want to count how many lines are there in the Testfile.txt.
using (StreamReader sr = new StreamReader("TestFile.txt"))
{
string line;
while ((line = sr.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
I already tried to put after the while loop if(line == null) sr.Close() but it doesn’t work.
Why not just read it into a
List<string>and then build an array from that? Or more simply still, just callFile.ReadAllLines:While you could reset the underlying stream and flush the buffer in the reader, I wouldn’t do so – I’d just read it all once in a way that doesn’t require you to know the size up-front.
(In fact, I’d try to use a
List<string>instead of astring[]anyway – they’re generally more pleasant to use. Read Eric Lippert’s blog post on the subject for more information.)