我正在使用这两个函数来读写大文件(写入多个文件)。我想保留函数中的文件操作,因为这些行可能是从其他源读取/写入的。协同/反应式扩展 - 写入行
更新: C#没有真正的协程。 Reactive扩展是否是一个很好的用例?
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' – 2014-09-03 13:58:46
是否需要一次处理一行(例如非常大的文件)? Otherweise,File.ReadAllLines没问题。 – WeSt 2014-09-03 14:01:23
@SriramSakthivel:你只需要小心不要使用'File.WriteAllLines(“path”,File.ReadLines(“path”))''它会尝试写入你正在阅读的文件。 – 2014-09-03 14:02:52