【问题标题】:Save x amount of lines with StreamWriter and Console output使用 StreamWriter 和控制台输出保存 x 行
【发布时间】:2014-02-02 18:19:38
【问题描述】:

我有一个 Windows (C#) 命令行程序,它使用 StreamWriter 将控制台输出重定向到文本文件。这工作正常,但我只需要日志的最后 100 行,并且我每秒向日志文件写入大约 5 次,所以你可以想象这个文件可能有多大。我想做的是每 100 行左右的 StreamWriter 完全覆盖文件。有没有人有这样做的有效方法?

我当前的代码(正在运行)是:

var streamWriter = new StreamWriter(
    string.Format("{0}/logs/{1}.txt", 
    baseDir, DateTime.Now.ToString("dd-MM-yyyy")), 
    false, 
    Encoding.ASCII, 
    16384
);

streamWriter.AutoFlush = true;
var originalOut = Console.Out;
Console.SetOut(streamWriter);

// .. do my stuff and write lines...
Console.WriteLine("This is a test...");

// ..finished..
Console.SetOut(originalOut);
streamWriter.Dispose();

如何调整它以每 100 行覆盖一次日志文件?

提前致谢!

【问题讨论】:

  • 为什么我被否决了?这是一个真正的问题,需要一种有效的方法来解决这个问题。
  • genuine question? :)) 太自信了?无论如何,我看不到无效的实施。
  • 是的,代码确实有效,但它会无休止地将行写入日志文件,我真的只需要最后 100 行,所以我只希望日志文件中存在这 100 行。希望这是有道理的! :)
  • 你可以试试 CodeReview,一个更好的 Stack Exchange 网站。它主要用于修剪代码或修复已经顺利运行的代码
  • @Daveo:您是否需要保留在调用 Dispose 之前编写的最后 100 行,或者您是否需要日志文件在任何点包含最近的 100 行手术时间?

标签: c# .net windows


【解决方案1】:

这是我在my comment above中提出的建议的代码。

// Keeps most recent 100–200 lines.
List<string> cache = new List<string>();

while (true)
{
    // Create new writer, overwriting old file (if it already exists).
    using (var streamWriter = new StreamWriter(/* ... */))
    {
        // Write last 100 lines from cache.
        if (cache.Count > 0)
            streamWriter.WriteLine(string.Join(Environment.NewLine, cache));

        // Get next line and write it.
        string line = /* your implementation */
        streamWriter.WriteLine(line);

        // Append to cache.
        cache.Add(line);

        // If cache limit reached, we need to recycle.
        if (cache.Count == 200)
        {
            // Keep only most recent 100 lines.
            cache = cache.Skip(100).ToList();

            // Start a new iteration, causing the file to be overwritten.
            continue;
        }
    }
}

【讨论】:

  • 我喜欢它。非常感谢。 :)
  • 干杯!我没有在我的代码中处理日期更改(因为我看不到你在你的代码中是如何处理它们的),但你可能需要为它们实现一些额外的逻辑。开始写入新一天的日志时请注意清除缓存。
猜你喜欢
  • 1970-01-01
  • 2022-12-12
  • 1970-01-01
  • 1970-01-01
  • 2021-12-30
  • 1970-01-01
  • 2018-09-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多