gpt4 book ai didi

c# - 协程/响应式(Reactive)扩展 - 写行

转载 作者:太空宇宙 更新时间:2023-11-03 19:06:58 25 4
gpt4 key购买 nike

我正在使用这两个函数来读取和写入大文件(写入多个文件)。我想在函数中保留文件操作,因为这些行可能是从其他来源读/写的。

更新: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.WriteAllLines。它会将序列中的所有行写入文件,并且不会为每一行打开/关闭文件。

关于c# - 协程/响应式(Reactive)扩展 - 写行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25646203/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com