I realize a program which basically imports data. The log of the import is built with a StringBuilder
, and then printed in a RichTextBox
, programmaticaly, in a new Window
.
I searched how to hightlight specific words and how to put in bold lines containing specific characters.
For example, part of my log looks like this :
I didn't found a "magic solution" in WPF for this, so I made a code which is not very optimized / proper. This is my code :
TextRange tr;
foreach(var line in finalText.Split(new string[] { Environment.NewLine }, StringSplitOptions.None)
{
tr = new TextRange(rtb.Document.ContentEnd, rtb.Document.ContentEnd);
foreach (var word in line.Split(' '))
{
tr = new TextRange(rtb.Document.ContentEnd, rtb.Document.ContentEnd);
tr.Text = word + ' ';
if (line.IndexOf("====", StringComparison.OrdinalIgnoreCase) >= 0)
{
tr.ApplyPropertyValue(TextElement.FontWeightProperty, FontWeights.Bold);
}
else if (line.IndexOf("Statut", StringComparison.OrdinalIgnoreCase) >= 0)
{
tr.ApplyPropertyValue(TextElement.FontSizeProperty, (double)14);
}
else if (line.IndexOf("Fin", StringComparison.OrdinalIgnoreCase) >= 0)
{
tr.ApplyPropertyValue(TextElement.FontSizeProperty, (double)14);
}
else
{
tr.ApplyPropertyValue(TextElement.FontWeightProperty, FontWeights.Normal);
tr.ApplyPropertyValue(TextElement.FontSizeProperty, (double)12);
}
if (word.IndexOf("Succès", StringComparison.OrdinalIgnoreCase) >= 0 || word.IndexOf("Succes", StringComparison.OrdinalIgnoreCase) >= 0)
{
tr.ApplyPropertyValue(TextElement.ForegroundProperty, Brushes.Green);
}
else if (word.IndexOf("Erreur", StringComparison.OrdinalIgnoreCase) >= 0)
{
tr.ApplyPropertyValue(TextElement.ForegroundProperty, Brushes.Red);
}
else if (word.IndexOf("Info", StringComparison.OrdinalIgnoreCase) >= 0)
{
tr.ApplyPropertyValue(TextElement.ForegroundProperty, Brushes.DarkOrange);
}
else if (word.IndexOf("Modif", StringComparison.OrdinalIgnoreCase) >= 0)
{
tr.ApplyPropertyValue(TextElement.ForegroundProperty, Brushes.DarkBlue);
}
else
{
tr.ApplyPropertyValue(TextElement.ForegroundProperty, Brushes.Black);
}
}
tr.Text += Environment.NewLine;
}
Note : finalText
is the String
representing the log and rtb
is the RichTextBox.
As you can see when a entire line needs to be in bold, I re-apply the property to each word because I need a new TextRange
for each new word, in order to change the color.
The problem is that with only a few lines of log (let's say 50 lines
), I found my code to be very slow : this single piece of code takes up to 3 seconds
to complete. The import itself (opening files, analyzing, making operations in database on a lot of data) does not take such time.
Any hint to reduce this time ?
Thank you in advance.