I have a TextReader object.

Now, I want to stream the whole content of the TextReader to a File. I cannot use ReadToEnd() and write all to a file at once, because the content can be of high size.

Can someone give me a sample/tip how to do this in Blocks?

1

3 Answers

using (var textReader = File.OpenText("input.txt")) using (var writer = File.CreateText("output.txt")) { do { string line = textReader.ReadLine(); writer.WriteLine(line); } while (!textReader.EndOfStream); } 
2

Something like this. Loop through the reader until it returns null and do your work. Once done, close it.

String line; try { line = txtrdr.ReadLine(); //call ReadLine on reader to read each line while (line != null) //loop through the reader and do the write { Console.WriteLine(line); line = txtrdr.ReadLine(); } } catch(Exception e) { // Do whatever needed } finally { if(txtrdr != null) txtrdr.Close(); //close once done } 

Use TextReader.ReadLine:

// assuming stream is your TextReader using (stream) using (StreamWriter sw = File.CreateText(@"FileLocation")) { while (!stream.EndOfStream) { var line = stream.ReadLine(); sw.WriteLine(line); } } 

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.