Graham
Graham

Reputation: 8151

Remove a line from a System.IO.StringWriter

I have a piece of code that is adding lines of text to a System.IO.StringWriter.

When it gets above a certain size, I want to purge lines from the beginning.

How do I do that? Can it be done?

System.IO.StringWriter log = new System.IO.StringWriter();
log.WriteLine("some text");
log.WriteLine("more text");

// some how remove the first line ????

Upvotes: 1

Views: 805

Answers (3)

DarkSquirrel42
DarkSquirrel42

Reputation: 10257

System.IO.StringWriter log = new System.IO.StringWriter();
log.WriteLine("some text");
log.WriteLine("more text");

// some how remove the first line ????

var sb = log.GetStringBuilder(); //get the underlying StringBuilder
var newLinePosition = sb.ToString().IndexOf(Environment.NewLine); //find the first newline
sb.Remove(0, newLinePosition + Environment.NewLine.Length); //remove from start to the newline... including the newline itself

Upvotes: 4

Steve
Steve

Reputation: 216293

A possible solution to your problem involves the use of the Queue class. You can add your text to this object and when it reaches a certain size you start trimming away the initial data

For example

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());
}

Upvotes: 6

FalcoGer
FalcoGer

Reputation: 2457

You can, instead of writing to a stream write to a different data structure (such as a list) and use an iterator to loop over your lines and replace them if you hit a certain threshold.

List<string> log = new List<string>();
int idx = 0;

//...
if (idx > 10) // your max amount of messages
{
    idx = 0;
}
if (log.Count < idx)
{
    log.Add("more Text");
}
else
{
    log[idx] = "more Text";
}

of course you should wrap this in a class for logging.

Upvotes: 1

Related Questions