c# - How to format a number into a fixed string size, in .NET? -


i'm displaying guid's , numbers in simple text output report. how can keep length of each string 'fixed'.

eg. currently, happening. (bad).

[waworkerhost.exe] +-----------------------------------------------------------+ [waworkerhost.exe] +  ravendb initialization report                            + [waworkerhost.exe] +  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^                            + [waworkerhost.exe] +  o) tenant id: 50f1bf7f-7936-4aa9-aeca-e47b1d61bb85       + [waworkerhost.exe] +  o) number of documents: 87                            + [waworkerhost.exe] +  o) number of indexes: 5                            + [waworkerhost.exe] +  o) number of ~stale indexes: 0                            + [waworkerhost.exe] +-----------------------------------------------------------+ 

and i'm after...

[waworkerhost.exe] +-----------------------------------------------------------+ [waworkerhost.exe] +  ravendb initialization report                            + [waworkerhost.exe] +  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^                            + [waworkerhost.exe] +  o) tenant id: 50f1bf7f-7936-4aa9-aeca-e47b1d61bb85       + [waworkerhost.exe] +  o) number of documents: 87                               + [waworkerhost.exe] +  o) number of indexes: 5                                  + [waworkerhost.exe] +  o) number of ~stale indexes: 0                           + [waworkerhost.exe] +-----------------------------------------------------------+ 

cheers!

(note: guid fixed length, line has 'hardcoded' spaces.

with string formatting:

static string boxline(int totalwidth, string format, params object[] args) {     string s = string.format(format, args);     return "+ " + s.padright(totalwidth - 4) + " +"; }  static string boxstartend(int totalwidth) {     return "+" + new string('-',totalwidth-2) + "+"; } 

call string.format width in there:

static void main(string[] args) {     const int boxwidth = 40;      console.writeline( boxstartend(boxwidth) );     console.writeline( boxline(boxwidth, "does work: {0} {1}", 42, 64) );     console.writeline( boxline(boxwidth, " -->yep<--") );     console.writeline( boxstartend(boxwidth) );      console.read();     } 

output:

+--------------------------------------+ + work: 42 64                + +  -->yep<--                           + +--------------------------------------+ 

Comments