Поток TextReader в файл
У меня есть TextReader-объект. Теперь я хочу передать все содержимое TextReader в файл. Я не могу использовать ReadToEnd() и записать все в файл одновременно, потому что содержимое может быть большого размера. Может кто-нибудь дать мне образец / совет, как это сделать в блоках?
Благодарю.
3 ответа
Решение
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);
}
}