我有一段代码将文本行添加到 System.IO.StringWriter。
当它超过一定大小时,我想从头开始清除行。
我怎么做?可以做到吗?
System.IO.StringWriter log = new System.IO.StringWriter();
log.WriteLine("some text");
log.WriteLine("more text");
// some how remove the first line ????
Run Code Online (Sandbox Code Playgroud)
您的问题的一个可能解决方案是使用Queue 类。您可以将文本添加到此对象,当它达到一定大小时,您开始修剪初始数据
例如
void Main()
{
int maxQueueSize = 50;
var lines = File.ReadAllLines(filePath);
Queue<string> q = new Queue<string>(lines);
// Here you should check for files bigger than your limit
....
// Trying to add too many elements
for (int x = 0; x < maxQueueSize * 2; x++)
{
// Remove the first if too many elements
if(q.Count == maxQueueSize)
q.Dequeue();
// as an example, add the x converted to string
q.Enqueue(x.ToString());
}
// Back to disk
File.WriteAllLines(filePath, q.ToList());
}
Run Code Online (Sandbox Code Playgroud)