我有一个TextReader对象。
现在,我想将TextReader的全部内容流到一个文件中。我不能一次使用ReadToEnd()并将所有内容写到文件中,因为内容可以是很大的。
有人能给我一个样品/提示,如何分块做这件事?
发布于 2014-07-12 16:42:37
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-12 16:43:05
就像这样。循环遍历阅读器,直到它返回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-12 16:45:29
使用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);
}
}https://stackoverflow.com/questions/24714947
复制相似问题