Reputation: 93
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.
Upvotes: 1
Views: 568
Reputation: 1503290
Why not just read it into a List<string>
and then build an array from that? Or more simply still, just call File.ReadAllLines
:
string[] lines = File.ReadAllLines("TestFile.txt");
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 a string[]
anyway - they're generally more pleasant to use. Read Eric Lippert's blog post on the subject for more information.)
Upvotes: 10
Reputation: 6890
You can do it by setting the BaseStream
Position
property to 0.
If you cannot (example would be a HttpWebResponse stream) then a good option would be to copy the stream to a MemoryStream
...there you can set Position to 0 and restart the Stream as much as you want.
Stream s = new MemoryStream();
StreamReader sr = new StreamReader(s);
// later... after we read stuff
s.Position = 0;
Upvotes: 4