3

我有一个TextReader对象。

现在,我想将整个内容流式传输TextReader到一个文件。我不能ReadToEnd()一次使用并将所有内容写入文件,因为内容可能很大。

有人可以给我一个示例/提示如何在 Blocks 中执行此操作吗?

4

3 回答 3

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);
}
于 2014-07-12T16:42:37.607 回答
1

像这样的东西。遍历阅读器,直到它返回null并完成您的工作。完成后,关闭它。

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
}
于 2014-07-12T16:43:05.083 回答
0

使用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);
    }
}
于 2014-07-12T16:45:29.683 回答