Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Align Text Right in Console

Tags:

string

c#

console

Is there a way for me to align text to the right side of my Console Application? I want to print a String with "[ok]" on the same line but on the right hand side. Like you see when booting a Linux Distro.

like image 576
jacksmith Avatar asked Aug 02 '11 14:08

jacksmith


2 Answers

You could do something like this, if you're using Console.WriteLine...

Console.WriteLine("{0,-20} {1,20}", "Finished!", "[ok]");

Assuming your lines are 40 characters wide, the word "Finished" will be left-aligned in a 20 character field, and then the word "[ok]" will be right-aligned in another 20 character field. So you end up with something like

Finished!                            [ok]
like image 112
Grant Winney Avatar answered Nov 07 '22 14:11

Grant Winney


I would suggest using curses as @Oded said.

If you really don't want to use any third party libraries, you can use Console.BufferWidth to get size of console and then Console.Console.CursorLeft to set column position.

Console.CursorLeft = Console.BufferWidth - 4;
Console.Write("[ok]");

The above prints [ok] at the end of the current line, leaving cursor at the first column, next line

like image 40
Martin Brenden Avatar answered Nov 07 '22 16:11

Martin Brenden