Stream TextReader to a File

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?

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); } } 

ncG1vNJzZmirpJawrLvVnqmfpJ%2Bse6S7zGiorp2jqbawutJoaW1vYWmGdYOOrKurnZGierWx162pnpmUmr9uwM5mmGaemaGy

 Share!