BlackWaspTM

This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

Input / Output
.NET 3.5+

A Text-Based Box Generator

When working with console applications, or when adding to a log file, it is often useful to highlight elements of the text. One way in which to achieve this is to draw a box around the text, using standard symbols from the available character set.

Building the Box

The final task is to combine the borders and the text into a single string. To avoid multiple string operations we'll use a StringBuilder. First we'll create the top border, then add the text lines and finally the bottom border. The lines are added in a separate method, which loops through the array adding a line with left and right border characters for each element:

private string BuildBox(IEnumerable<string> padded, int width)
{
    StringBuilder sb = new StringBuilder();
    sb.Append(_border[TL]).Append(_border[T], width).Append(_border[TR]).AppendLine();
    AddLines(padded, width, sb);
    sb.Append(_border[BL]).Append(_border[B], width).Append(_border[BR]);
    return sb.ToString();
}

private void AddLines(IEnumerable<string> padded, int width, StringBuilder sb)
{
    foreach (string line in padded)
    {
        sb.Append(_border[L]).Append(line).Append(_border[R]).AppendLine();
    }
}

Using the Box Generator

You can now try out the BoxGenerator class. The following example constructs a new instance, specifying the use of the double-border style. It then outputs some text in a box.

var generator = new BoxGenerator(BoxStyle.Double);

string[] text = new string[]
{
    "TEST",
    "----",
    "",
    "The quick brown fox jumps over the lazy dog."
};

Console.WriteLine(generator.GenerateBox(text, 75));

/* OUTPUT

╔════════════════════════════════════════════╗
║TEST                                        ║
║----                                        ║
║                                            ║
║The quick brown fox jumps over the lazy dog.║
╚════════════════════════════════════════════╝

*/
9 March 2014