Last active
August 29, 2015 14:14
-
-
Save ascjones/729f33f9069106ba5b5f to your computer and use it in GitHub Desktop.
ConsoleProgressBar
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
class ProgressBar | |
{ | |
private const char Start = '['; | |
private const char End = ']'; | |
private const char InProgress = '>'; | |
private const char Done = '-'; | |
private readonly int totalSize; | |
private readonly int progressLength; | |
private readonly int chunkSize; | |
private readonly ConsoleColor color; | |
private readonly DateTime started; | |
public ProgressBar(int totalSize, int progressLength, ConsoleColor color) | |
{ | |
this.color = color; | |
this.totalSize = totalSize; | |
this.progressLength = progressLength; | |
chunkSize = totalSize / progressLength; | |
started = DateTime.UtcNow; | |
var whitespace = string.Join("", Enumerable.Range(0, progressLength).Select(_ => " ")); | |
Colour(() => Console.Write("{0}{1}{2}", Start, whitespace, End)); | |
var progressNumbers = string.Format(" {0} of {1} {2}%", 0, totalSize, 0); | |
Colour(() => Console.Write(progressNumbers), ConsoleColor.Green); | |
} | |
public void UpdateProgress(int pos) | |
{ | |
Colour(() => | |
{ | |
// progress bar | |
Console.SetCursorPosition(1, Console.CursorTop); | |
var arrow = new string(Enumerable.Range(0, pos/chunkSize).Select(_ => Done).ToArray()); | |
Console.Write("{0}{1}", arrow, InProgress); | |
}); | |
Colour(() => | |
{ | |
// progress numbers | |
Console.SetCursorPosition(progressLength + 3, Console.CursorTop); | |
double perc = Math.Round((pos / (double) totalSize) * 100, 2); | |
string remaining = ""; | |
if (pos > 0) | |
{ | |
var perEvent = (DateTime.UtcNow - started).Ticks / pos; | |
var timeleft = TimeSpan.FromTicks((totalSize - pos) * perEvent); | |
remaining = string.Format("{0} remaining", timeleft.ToString(@"hh\:mm\:ss")); | |
} | |
Console.Write(" {0} of {1} {2}% {3}", pos, totalSize, perc, remaining); | |
}, ConsoleColor.Green); | |
} | |
private void Colour(Action print) | |
{ | |
Colour(print, color); | |
} | |
private void Colour(Action print, ConsoleColor consoleColor) | |
{ | |
Console.ForegroundColor = consoleColor; | |
print(); | |
Console.ForegroundColor = ConsoleColor.White; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment