Created
July 25, 2011 20:35
-
-
Save prabirshrestha/1105125 to your computer and use it in GitHub Desktop.
C# Console Progress
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class ProgressBar | |
{ | |
private int _lastOutputLength; | |
private readonly int _maximumWidth; | |
public ProgressBar(int maximumWidth) | |
{ | |
_maximumWidth = maximumWidth; | |
Show(" [ "); | |
} | |
public void Update(double percent) | |
{ | |
// Remove the last state | |
string clear = string.Empty.PadRight(_lastOutputLength, '\b'); | |
Show(clear); | |
// Generate new state | |
int width = (int)(percent / 100 * _maximumWidth); | |
int fill = _maximumWidth - width; | |
string output = string.Format("{0}{1} ] {2}%", string.Empty.PadLeft(width, '='), string.Empty.PadLeft(fill, ' '), percent.ToString("0.0")); | |
Show(output); | |
_lastOutputLength = output.Length; | |
} | |
private void Show(string value) | |
{ | |
Console.Write(value); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
static void Main(string[] args) | |
{ | |
var progress = new ProgressBar(60); | |
for (int i = 0; i < 101; i++) | |
{ | |
progress.Update(i); | |
System.Threading.Thread.Sleep(50); | |
} | |
Console.WriteLine(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It's useful! I even on older versions! Love it