Formatted Printing on Console Application
I've got a console application that stores information. I have an option that the end user can select that will print the colon-delimited file into a formatted print. I want several different columns, but I want to control the width. I know certain information cannot be longer than X number of characters. For instance I want to print something like:
Number | Name | Address | Zip |
1 Frank 123 Main St. 47887
Does C# have any functionality that will allow this? I was thinking Console.Write would work, but I want to be able to pad each side with whitespace.
Any information would be greatly appreciated!
Re: Formatted Printing on Console Application
Padding is specified in String.Format with "{0,-xx}" where xx is the number of characters to pad.
So you can print out the header information with
Code:
var formatter = "{0,-10}{1,-50}{2,-60}{3,-10}";
Console.WriteLine(String.Format(formatter, "Number", "Name", "Address", "Zip"));
Each entry could be printed as (assuming a class name Entry contains each item data):
Code:
Console.WriteLine(String.Format(formatter, entry.Number, entry.Name, entry.Address, entry.Zip));
Another way to do this for simple apps is to override a class's ToString() method.
Code:
public class Entry
{
public int Number { get; set; }
public string Name { get; set; }
public string Address { get; set; }
public string Zip { get; set; }
public override ToString()
{
return String.Format(Formatter, Number, Name, Address, Zip);
}
public static string Formatter = "{0,-10}{1,-50}{2,-60}{3,-10}";
}
Then you can print the header and each line item as follow (assuming entries are a List<Entry> collection):
Code:
Console.WriteLine(String.Format(Entry.Formatter, "Number", "Name", "Address", "Zip"));
foreach(var entry in entries)
{
Console.WriteLine(entry);
}
See String.Format in msdn for more info.