我有一个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行覆盖一次日志文件?
提前致谢!
答案 0 :(得分: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;
}
}
}