C# progress bar in Console app without it getting piped to a text file - similar to C++ cerr and flush

1.2k Views Asked by At

I'm working on a file that outputs text using a pipe like this:

 > main.exe | set-content image.ppm -encoding String

The problem is that I would like to have a progress bar without it getting piped into the text file. Console.Error.Write() seems to do this, however I can't get the countdown to happen in place, rather than a bunch of strings happening in a row. I've tried using Console.SetCursorPosition() in a few different ways, but maybe I'm using it improperly.

Here is how it would work with C++, and I'm trying to write it with C#:

std::cout << "P3\n" << image_width << ' ' << image_height << "\n255\n";

for (int j = image_height - 1; j >= 0; --j) {
    
    //progress bar
    std::cerr << "\rScanlines remaining: " << j << ' ' << std::flush;
    
    //output to ppm file
    for (int i = 0; i < image_height; ++i) {
        auto r = double(i) / (image_width - 1);
        auto g = double(j) / (image_height - 1);
        auto b = 0.25;

        int ir = static_cast<int>(255.999 * r);
        int ig = static_cast<int>(255.999 * g);
        int ib = static_cast<int>(255.999 * b);

        std::cout << ir << ' ' << ig << ' ' << ib << '\n';
    }

C# (can't get the progress bar to work properly)

    Console.WriteLine("P3");
    Console.WriteLine($"{image_width} {image_height}");
    Console.WriteLine(255);

    for (int j = image_height - 1; j >= 0; j--)
    {
        
        //progress bar
        //Console.SetCursorPosition(0, Console.CursorLeft);
        //Console.SetCursorPosition(left, top);
        Console.Error.Write($"Scanlines Remaining: {j}");
        
        //output to ppm file
        for (int i = 0; i < image_height; i++)
        {
            var r = (double)i / (image_width - 1);
            var g = (double)j / (image_height - 1);
            var b = 0.25;

            int ir = (int)(255.999 * r);
            int ig = (int)(255.999 * g);
            int ib = (int)(255.999 * b);

            Console.WriteLine($"{ir} {ig} {ib}");
        }
    }

I'd like the progress bar to smoothly show the countdown instead of this: countdown

0

There are 0 best solutions below