Why using StringBuilder with Replace it's not replacing the strings?

rhodanny 166 Reputation points
2023-12-30T05:07:43.5133333+00:00

I did a test.

Created a class name Logger and inside the class added some methods one of them is LogStartDownload and the [Status] is Downloading in progress: $"[Status] Downloading in progress"

and a method LogDownloadCompleted where I want to replace the string $"[Status] Downloading in progress" with the string "$[Status]: Download Cancelled"

this is how i'm using it in form1:

but when I click the button it's not replacing the left side is stay as before without any change: [Status] Downloading in progress and I used a breakpoint and it's getting to the line Replace in the Logger class but never make the replacing.

screenshot of the appplication running after I clicked the button:

the [Status] Downloading in progress should be replaced but it's not.

notR1

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Downloading_Files
{
    public partial class Form1 : Form
    {
        Logger logger = new Logger();
        private TimeSpan _elapsedTime;

        public Form1()
        {
            InitializeComponent();

            logger.LogStartDownload("Hello", "Hello World");
            logger.GetLog(richTextBox1);
        }

        private void btnReplace_Click(object sender, EventArgs e)
        {
            logger.LogDownloadCompleted(false, _elapsedTime, true);
            logger.LogDownloadCancelled();

            logger.GetLog(richTextBox1);
        }
    }
}

// Logger.cs
using System;
using System.Text;
using System.Windows.Forms;

namespace Downloading_Files
{
    public class Logger
    {
        private StringBuilder logBuilder = new StringBuilder();
        private TimeSpan elapsedTime; // Add a private variable to store elapsed time

        public void LogStartDownload(string fileName, string fileUrl)
        {
            logBuilder.AppendLine($"[Start Time]: {DateTime.Now}");
            logBuilder.AppendLine($"[File Name]: {fileName}");
            logBuilder.AppendLine($"[File URL]: {fileUrl}");
            logBuilder.AppendLine($"[Status] Downloading in progress");
        }

        public void LogDownloadProgress(double percentage, double speed, long totalBytes, long contentLength, TimeSpan elapsedTime)
        {
            this.elapsedTime = elapsedTime; // Store elapsed time for later use
            logBuilder.AppendLine($"[Progress]: {percentage}%");
            logBuilder.AppendLine($"[Downloaded]: {FormatBytes(totalBytes)} / {FormatBytes(contentLength)}");
            logBuilder.AppendLine($"[Download Speed]: {FormatBytes(speed)}/s");
            logBuilder.AppendLine($"[Time Elapsed]: {FormatTimeSpan(elapsedTime)}");
        }

        public void LogDownloadCompleted(bool isSuccess, TimeSpan elapsedTime, bool isCancelled)
        {
            this.elapsedTime = elapsedTime; // Update elapsed time when the download completes
            if (!isCancelled)
            {
                logBuilder.Replace($"[Status] Downloading in progress", $"[Status]: Download {(isSuccess ? "Completed Successfully" : "Failed")}");
                //logBuilder.AppendLine($"[Status]: Download {(isSuccess ? "Completed Successfully" : "Failed")}");
            }
            else
            {
                logBuilder.Replace('\n', '\r');
                logBuilder.Replace($"[Status] Downloading in progress", "$[Status]: Download Cancelled");
                
                //logBuilder.AppendLine($"[Status]: Download Cancelled");
            }
            logBuilder.AppendLine($"[Elapsed Time]: {FormatTimeSpan(elapsedTime)}");
            logBuilder.AppendLine($"[End Time]: {DateTime.Now}");
            logBuilder.AppendLine(); // Add a space line between download logs
        }

        public void LogDownloadCompleted()
        {
            logBuilder.AppendLine("[Status]: All downloads completed");
            logBuilder.AppendLine();
        }

        public void LogDownloadCancelled()
        {
            logBuilder.AppendLine("[Status]: Operation cancelled and all file have been deleted");
            logBuilder.AppendLine();
        }

        public string GetLog(RichTextBox richTextBoxLogger)
        {
            string log = logBuilder.ToString();
            richTextBoxLogger.AppendText(log);
            logBuilder.Clear(); // Clear the log after appending it once

            return log;
        }

        private string FormatBytes(double bytes)
        {
            const int scale = 1024;
            string[] units = { "B", "KB", "MB", "GB", "TB", "PB", "EB" };

            if (bytes <= 0)
            {
                return "0 B";
            }

            int magnitude = (int)Math.Floor(Math.Log(bytes, scale));
            int index = Math.Min(magnitude, units.Length - 1);

            double adjustedSize = bytes / Math.Pow(scale, index);
            string format = (index >= 0 && index < 3) ? "F2" : "F0";

            return $"{adjustedSize.ToString(format)} {units[index]}";
        }

        private string FormatTimeSpan(TimeSpan timeSpan)
        {
            return $"{timeSpan.Hours:D2}:{timeSpan.Minutes:D2}:{timeSpan.Seconds:D2}";
        }
    }
}
Developer technologies Windows Forms
Developer technologies C#
0 comments No comments
{count} votes

Accepted answer
  1. WayneAKing 4,931 Reputation points
    2023-12-30T08:24:32.78+00:00

    I suspect that no match is found for the Replace because you have cleared logBuilder in GetLog. When you stop on a breakpoint at the Replace line check the contents of logBuilder in the Debugger and make sure it isn't empty.

    As an experiment to see if it makes a difference in the test results, try changing GetLog to the followimg.

    This is just a test to see if it moves you forward. Clearly some additional changes will be needed.

        richTextBoxLogger.Clear(); // erase old contents
    
        string log = logBuilder.ToString();
        richTextBoxLogger.AppendText(log);
    
        //logBuilder.Clear(); // Clear the log after appending it once
    
        return log;
    
    
    0 comments No comments

0 additional answers

Sort by: Most helpful

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.