Saltar al contenido

ejemplo de código de consola de barra de progreso c #

Luego de de una prolongada compilación de datos solucionamos esta traba que tienen ciertos lectores. Te dejamos la solución y deseamos servirte de gran ayuda.

Ejemplo 1: barra de progreso de la consola de c #

// RepeatprivatestaticstringRepeat(string str,int times)returnstring.Concat(Enumerable.Repeat(str, times));// Progress BarprivatestaticvoidProgressBar(int progress,int total,int chunks =30,ConsoleColor completeColour = ConsoleColor.Green,ConsoleColor remainingColour = ConsoleColor.Gray,string symbol ="■",bool showPercent =true)//Draw Blank Progress Bar
	Console.CursorLeft =0;
	Console.Write("  [");
	Console.CursorLeft = chunks +3;
	Console.Write("]");
	Console.CursorLeft =3;float chunk =(float) chunks / total;// Chunk Calculationsdouble completeRaw = Math.Ceiling((double) chunk * progress);int complete =(int) Math.Ceiling((double) chunk * progress);int remaining = chunks - complete;// Draw Progress
	Console.ForegroundColor = completeColour;
	Console.Write(Repeat(symbol, complete));
	Console.ForegroundColor = remainingColour;
	Console.Write(Repeat(symbol, remaining));// Show Percent
	Console.CursorLeft = chunks +4;
	Console.ResetColor();if(showPercent)int percent =(int)((float) progress /(float) total *100);
		Console.Write($" Repeat(" ",3- percent.ToString().Length)percent %");

Ejemplo 2: agregar progreso en la aplicación de consola c #

// ---	ProgressBarusingSystem;usingSystem.Text;usingSystem.Threading;/// <summary>/// An ASCII progress bar/// summary>publicclassProgressBar:IDisposable,IProgress<double>/-";

	private readonly Timer timer;

	private double currentProgress = 0;
	private string currentText = string.Empty;
	private bool disposed = false;
	private int animationIndex = 0;

	public ProgressBar() 
		timer = new Timer(TimerHandler);

		// A progress bar is only for temporary display in a console window.
		// If the console output is redirected to a file, draw nothing.
		// Otherwise, we'll end up with a lot of garbage in the target file.
		if (!Console.IsOutputRedirected) 
			ResetTimer();
		
	

	public void Report(double value) 
		// Make sure value is in [0..1] range
		value = Math.Max(0, Math.Min(1, value));
		Interlocked.Exchange(ref currentProgress, value);
	

	private void TimerHandler(object state) 
		lock (timer) 
			if (disposed) return;

			int progressBlockCount = (int) (currentProgress * blockCount);
			int percent = (int) (currentProgress * 100);
			string text = string.Format("[01]2,3%3",newstring('#', progressBlockCount),newstring('-', blockCount - progressBlockCount),
				percent,
				animation[animationIndex++% animation.Length]);UpdateText(text);ResetTimer();privatevoidUpdateText(string text)// Get length of common portionint commonPrefixLength =0;int commonLength = Math.Min(currentText.Length, text.Length);while(commonPrefixLength < commonLength && text[commonPrefixLength]== currentText[commonPrefixLength])
			commonPrefixLength++;// Backtrack to the first differing characterStringBuilder outputBuilder =newStringBuilder();
		outputBuilder.Append('b', currentText.Length - commonPrefixLength);// Output new suffix
		outputBuilder.Append(text.Substring(commonPrefixLength));// If the new text is shorter than the old one: delete overlapping charactersint overlapCount = currentText.Length - text.Length;if(overlapCount >0)
			outputBuilder.Append(' ', overlapCount);
			outputBuilder.Append('b', overlapCount);

		Console.Write(outputBuilder);
		currentText = text;privatevoidResetTimer()
		timer.Change(animationInterval, TimeSpan.FromMilliseconds(-1));publicvoidDispose()lock(timer)
			disposed =true;UpdateText(string.Empty);//------------ MainusingSystem;usingSystem.Threading;staticclassProgramstaticvoidMain()
		Console.Write("Performing some task... ");using(var progress =newProgressBar())for(int i =0; i <=100; i++)
				progress.Report((double) i /100);
				Thread.Sleep(20);
		Console.WriteLine("Done.");

Más adelante puedes encontrar las críticas de otros administradores, tú además puedes insertar el tuyo si dominas el tema.

¡Haz clic para puntuar esta entrada!
(Votos: 0 Promedio: 0)



Utiliza Nuestro Buscador

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *