Formatting Console Output in C#
Yesterday I decided to modify a utlity I wrote to assist with copying Banner permissions from one user to another. I decided to add a list of the actual classes and objects that the destination user would receive as a result of the copy. This was a fairly easy modification, but as usual, I found myself spending most of my time on the easiest part of the project.
I naively assumed that C# would have some automagic way of display columns. While there may be a more official way to do it, nothing seemed to fit my scenario perfectly.
The average user has between 15 and 30 classes, but some have much more. I wanted to shorten the length, page wise, of the output. This was for purpose of readability. As I’m looping through a query result, my initial code looked something like this:
while (reader.Read()) { Console.WriteLine(reader[0].ToString()); }
I spent a good amount of time trying to use String.Format and things like it to try to turn this one column of output into two columns. The result? No success. Finally, I realized I was spending all my time trying to come up with the proper way to do something when there was most likely an easy, functional way to do this. I finally arrived at the following code:
int n = 0; while (reader.Read()) { if (n % 2 == 0) { Console.Write(reader[0].ToString().PadRight(30)); } else { Console.WriteLine(reader[0].ToString().PadRight(30)); } n++; }
The counter allows us to do an “every other time” operation by relying on whether or not the number is even or odd. Console.Write, as you should know, doesn’t append a return carriage, Console.WriteLine does.
PadRight(30) simply ensures that the output for each is a constant length. This prevents the “columns” from being misaligned.
There may be other, better ways to accomplish this. (And I welcome you to share them!) If you are dealing with a large amount of data and numerous columns, this is probably NOT the best approach. But if you’re looking for a functional, easy to implement means to an end, this may assist you.
