user1074030
user1074030

Reputation: 93

Problems with Streams in C#

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

Answers (2)

Jon Skeet
Jon Skeet

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

TehBoyan
TehBoyan

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

Related Questions