【发布时间】:2014-09-03 13:53:33
【问题描述】:
我正在使用这两个函数来读取和写入大文件(写入多个文件)。我想将文件操作保留在函数中,因为这些行可能是从其他来源读/写的。
更新: C# 并没有真正的协程。这是响应式扩展的好用例吗?
foreach (var line in ReadFrom("filename"))
{
try
{
.... // Some actions based on the line
var l = .....
WriteTo("generatedFile1", l);
}
catch (Exception e)
{
var l = ..... // get some data from line, e and other objects etc.
WriteTo("generatedFile2", l);
}
}
以下函数打开文件一次,直到读取所有行,然后关闭并释放资源。
private static IEnumerable<string> ReadFrom(string file)
{
string line;
using (var reader = File.OpenText(file))
{
while ((line = reader.ReadLine()) != null)
yield return line;
}
}
但是,以下函数写入行而不是读取行,它会为它写入的每一行打开和关闭文件。是否有可能以某种方式实现它,使其只打开一次文件并继续写入文件,直到发送 EOF?
private static void WriteTo(string file, string line)
{
if (!File.Exists(file)) // Remove and recreate the file if existing
using (var tw = File.CreateText(file))
{
tw.WriteLine(line);
}
else
using (var tw = new StreamWriter(file, true))
{
tw.WriteLine(line);
}
}
【问题讨论】:
-
你的第一种方法可以用
File.ReadLines代替,第二种方法可以用File.WriteLines代替 -
是否要求您一次处理一行(例如非常大的文件)?否则,File.ReadAllLines 很好。
-
@SriramSakthivel:您只需要注意不要使用
File.WriteAllLines("path",File.ReadLines("path")),它会尝试写入您当前正在阅读的文件。 -
@WeSt 在我看来,您基本上不应该使用
File.ReadAllLines。这是一种过时的方法。您实际上应该始终使用File.ReadLines。 OP 在此处的方法旨在做几乎相同的事情,只是它没有File.ReadLines中的错误。 -
@Servy:过于笼统,例如,如果您想修改现有文件,您不能在不将其读入内存的情况下使用
File.ReadLines。您也不能再次使用它(例如var lines=File.ReadLines(..); string header=lines.First();如果您现在尝试再次使用lines,您将看到ObjectDisposedException。
标签: c# .net system.reactive coroutine