将文本阅读器流写入文件

3

我有一个TextReader对象。

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

有人能给我一个示例/提示如何使用块来完成吗?


2
只需在循环中使用ReadLine(),直到它返回null - Hans Passant
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);
}

我认为这里使用do-while循环会更好。 - Yuval Itzchakov
你的代码无效。在“do”之前不应该读取一行,并且读取和写入的顺序混乱了。 - Yuval Itzchakov

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
}

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接