3

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?

Dale K
  • 25,246
  • 15
  • 42
  • 71
BennoDual
  • 5,865
  • 15
  • 67
  • 153

3 Answers3

5
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);
}
Tony
  • 86
  • 5
1

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
}
Rahul
  • 76,197
  • 13
  • 71
  • 125
0

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);
    }
}
Yuval Itzchakov
  • 146,575
  • 32
  • 257
  • 321