我有一个TextReader
对象。
现在,我想将整个TextReader
的内容流式传输到文件中。我不能使用ReadToEnd()
一次性将所有内容写入文件,因为内容可能非常大。
有人能给我一个示例/提示如何使用块来完成吗?
我有一个TextReader
对象。
现在,我想将整个TextReader
的内容流式传输到文件中。我不能使用ReadToEnd()
一次性将所有内容写入文件,因为内容可能非常大。
有人能给我一个示例/提示如何使用块来完成吗?
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);
}
类似这样。循环读取读取器,直到返回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
}
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);
}
}