为何StringBuilder的Replace方法无法替换旧字符串为新字符串?
问题原因分析
你的StringBuilder.Replace失效的核心原因是匹配字符串不包含换行符:
- 在
LogStartDownload中,你通过logBuilder.AppendLine($"[Status] Downloading in progress")添加状态行,AppendLine会自动在字符串末尾追加Environment.NewLine(Windows下为\r\n),因此logBuilder中实际存储的是"[Status] Downloading in progress\r\n"。 - 但你在
LogDownloadCompleted中调用Replace时,搜索的是不带换行的"[Status] Downloading in progress",自然找不到匹配项,替换操作也就不会生效。
另外,调用逻辑中存在重复调用LogDownloadCompleted的情况,且GetLog会清空logBuilder,但这不是本次替换失效的主因。
解决方案
方案1:修正匹配字符串(最简单直接)
把Replace的搜索字符串改为包含换行符的版本,确保和AppendLine添加的内容完全一致:
public void LogDownloadCompleted(bool isSuccess, TimeSpan elapsedTime, bool isCancelled) { this.elapsedTime = elapsedTime; string searchStr = $"[Status] Downloading in progress{Environment.NewLine}"; if (!isCancelled) { logBuilder.Replace(searchStr, $"[Status]: Download {(isSuccess ? "Completed Successfully" : "Failed")}{Environment.NewLine}"); } else { logBuilder.Replace(searchStr, $"[Status]: Download Cancelled{Environment.NewLine}"); } // 后续代码不变 logBuilder.AppendLine($"[Elapsed Time]: {FormatTimeSpan(elapsedTime)}"); logBuilder.AppendLine($"[End Time]: {DateTime.Now}"); logBuilder.AppendLine(); }
方案2:避免使用Replace,改用状态追踪(更健壮)
如果后续日志结构可能调整,建议单独维护下载状态,最后统一生成日志,避免依赖字符串替换:
public class Logger { private StringBuilder logBuilder = new StringBuilder(); private TimeSpan elapsedTime; // 新增状态变量追踪当前下载状态 private string currentStatus = string.Empty; public void LogStartDownload(string fileName, string fileUrl) { logBuilder.AppendLine($"[Start Time]: {DateTime.Now}"); logBuilder.AppendLine($"[File Name]: {fileName}"); logBuilder.AppendLine($"[File URL]: {fileUrl}"); // 仅记录状态,暂不写入logBuilder currentStatus = "[Status] Downloading in progress"; } public void LogDownloadProgress(double percentage, double speed, long totalBytes, long contentLength, TimeSpan elapsedTime) { this.elapsedTime = elapsedTime; 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; // 更新最终状态 if (!isCancelled) { currentStatus = $"[Status]: Download {(isSuccess ? "Completed Successfully" : "Failed")}"; } else { currentStatus = "[Status]: Download Cancelled"; } // 将状态插入到日志开头(可根据需求调整位置) logBuilder.Insert(0, currentStatus + Environment.NewLine); logBuilder.AppendLine($"[Elapsed Time]: {FormatTimeSpan(elapsedTime)}"); logBuilder.AppendLine($"[End Time]: {DateTime.Now}"); logBuilder.AppendLine(); } // 其余代码不变 }
额外优化:修正调用逻辑中的重复调用
在DownloadManager_DownloadCompleted中,存在两次调用LogDownloadCompleted的情况,会导致日志重复,建议调整为只调用一次:
private void DownloadManager_DownloadCompleted(object? sender, DownloadingCore.DownloadeCompletedEventArgs e) { progressBar1.Value = 0; _stopwatch.Stop(); if (e.IsSuccess && downloadsCounter > 0) { downloadsCounter--; } bool needLogCompleted = true; if(isCancelled && fileSavePath != null) { if (File.Exists(fileSavePath)) { File.Delete(fileSavePath); } logger.LogDownloadCancelled(); needLogCompleted = false; } if (needLogCompleted) { logger.LogDownloadCompleted(e.IsSuccess, _elapsedTime, isCancelled); } if (downloadsCounter == 0) { logger.LogDownloadCompleted(); Download.Enabled = true; } logger.GetLog(richTextBoxLogger); }
内容的提问来源于stack exchange,提问作者Shien
相关产品推荐
相关产品推荐

