simulate a progress bar in C# console

josesalaz 21 Reputation points
2023-04-20T19:14:26.5666667+00:00

Hello I have a code that gets the IdentifyingNumber of a program installed in Windows. However, during the time it gets the info, the console log is empty with no information about the progress of the code. I would need to show a progress bar to show the status of the code progress. At the end, the code prints an output4 = C3BCB0F2-5303-489D-AFAB-218B416D000D. Before, that print I would need to show the progress from 0 to 100 or something.
According to my understanding, one way to do this is to use a percentage-based progress bar. In this case, you would calculate the percentage of work completed by dividing the current amount of work by the total amount of work and multiplying by 100. For example, if you have completed 20 out of 100 tasks, the progress would be 20% (20/100 * 100).
But that's the problem, How do I know the total amount if the total amount is based in the variable CPU process.? I can not predict that value. I have tried with a function that I call but this just a static bar (useless)
I will appreciate any idea
Thanks

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
using System.Text.RegularExpressions;
using System.Threading;

namespace test
{
    public class Program
    {
        static void Main(string[] args)
        {

            int progress = 0;
            int max = 100;
            Console.Write(GetProgressBar(progress, max));



            ProcessStartInfo startInfo = new ProcessStartInfo("wmic");
            startInfo.UseShellExecute = false;
            startInfo.Arguments = "product where \"Name like '%Genetec Sipelia%'\" get IdentifyingNumber";
            startInfo.RedirectStandardOutput = true;

            Process process = new Process();
            process.StartInfo = startInfo;
            process.Start();
        

            // Update progress and wait for process to finish
            progress += 25;
            Console.Write(GetProgressBar(progress, max));
            process.WaitForExit();

            // Step 2: Read output and wait
            string output = process.StandardOutput.ReadToEnd();
            Thread.Sleep(1000);

            // Update progress
            progress += 25;
            Console.Write(GetProgressBar(progress, max));


            string input = output;
            string pattern2 = @"IdentifyingNumber\s+";

            string output3 = Regex.Replace(input, pattern2, "");

            string input3 = output3;
            string pattern3 = @"[{}]+";
            string output4 = Regex.Replace(input3, pattern3, "");

            // Update progress
            progress += 50;
            Console.WriteLine(GetProgressBar(progress, max));

            Console.WriteLine("the output4 :" + output4);



            Console.ReadLine();

        }

        static string GetProgressBar(int progress, int max)
        {
            int percent = (int)((double)progress / max * 100);
            int numFilled = (int)((double)progress / max * 50);
            string progressBar = $"|{new string('=', numFilled)}{new string(' ', 50 - numFilled)}| {percent}%";
            return progressBar;
        }
    }
}

Developer technologies | C#
{count} votes

2 answers

Sort by: Most helpful
  1. Karen Payne MVP 35,586 Reputation points Volunteer Moderator
    2023-04-21T01:07:50.8733333+00:00

    Check out Spectre.Console ProgressBar. Simple usage where you would place your work between the await and Increment.

    using Spectre.Console;
    
    namespace ProgressApp;
    
    partial class Program
    {
        static async Task Main(string[] args)
        {
    
            await AnsiConsole.Progress().StartAsync(async ctx =>
            {
    
                var gettingReadyTask = ctx.AddTask("[cyan]Getting things ready[/]");
                    
                while (!ctx.IsFinished)
                {
    
                    await Task.Delay(300);
                    gettingReadyTask.Increment(10.5);
    
                }
            });
    
            Console.ReadLine();
        }
    }
    
    1 person found this answer helpful.
    0 comments No comments

  2. Bruce (SqlWork.com) 78,006 Reputation points Volunteer Moderator
    2023-04-22T15:06:17.55+00:00

    The usual trick is to slow down the as time goes. Start with a time, say 10 seconds and update progress every second. Now at 5 seconds only update every 2 seconds, at the next half increase again.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.