Last active
March 1, 2021 20:52
-
-
Save iodar/b92a95ff68d37c3a47e152c0ccddd273 to your computer and use it in GitHub Desktop.
Simple Progress Bar Mock in C#
This file contains 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
// Shows how to implement a simple progress bar in C# | |
// usage: | |
// - create new terminal app: `dotnet new console --name terminal` | |
// - copy source code into `Program.cs` | |
// - compile and run `dotnet run` | |
// - have fun! | |
using System; | |
namespace terminal | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
// intial values for the progress bar | |
// will output [# ] 10% finished | |
// ... | |
// output [#### ] 40% finished | |
String barStart = "["; | |
String barEnd = "]"; | |
String barMiddle = ""; | |
// run in loop to mock behaviour of an operation | |
// that takes some time | |
for (int i = 1; i <= 10; i++) | |
{ | |
// increment the middle of the bar on each loop | |
barMiddle += "##"; | |
// fill remaining (yet missing) parts of the bar with | |
// empty space (spaces) to the right | |
String barMiddlePadded = barMiddle.PadRight(20, ' '); | |
// create progress bar from left to right | |
// append start, middle with progress and padded spaces | |
// and end to form full bar | |
String fullBar = barStart + barMiddlePadded + barEnd; | |
// carriage return to overwrite all characters on | |
// the current line; print progress bar, and | |
// percentage | |
Console.Write($"\r{fullBar} {i * 10}% finished"); | |
// sleep to mock long running operation | |
System.Threading.Thread.Sleep(500); | |
} | |
// carriage return to clear output after progress bar | |
Console.Write("\r"); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment