You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#向HTML指定位置插入多行时避免覆盖已插入内容的实现问题

问题解决方案

问题根源

你当前出现内容覆盖的核心原因有两个:

  1. 每次调用Create_Driver_Report方法时,读取的都是原始模板文件Driver_Reports.html,而非上一次修改后输出的drivers.html,之前的写入结果完全没有被保留,每次调用都是基于原始模板修改后覆盖写入drivers.html,自然只有最后一次调用的内容生效。
  2. 即使修改为读取输出文件,你每次都找<!--New Line Here-->标记的下一行插入,新内容会永远插在之前已插入内容的前面,顺序也不符合预期。

最优解决方案

不要在循环里反复读写文件(频繁IO性能非常差),改为一次性生成所有需要插入的内容,单次完成插入和写入操作,代码如下:

1. 预生成所有待插入内容

List<string> insertLines = new List<string>();
foreach (Drivers item in drivers)
{
    // 每条司机数据对应表格一行,用<tr>包裹
    insertLines.Add("<tr>");
    insertLines.Add($"<td>{item.Driver_ID}</td>");
    insertLines.Add($"<td>{item.Driver_Name}</td>");
    insertLines.Add($"<td>{item.Vehicle_ID}</td>");
    insertLines.Add($"<td>{item.Company_ID}</td>");
    insertLines.Add($"<td>{item.Company_Name}</td>"); 
    insertLines.Add("</tr>");              
}

2. 调整插入方法

private void Create_Driver_Report(List<string> insertLines)
{
    string templatePath = Get_Path("Driver_Reports.html");
    string outputPath = "drivers.html";
    string insertFlag = "<!--New Line Here-->";
    
    // 读取模板内容
    List<string> htmlContent = File.ReadAllLines(templatePath).ToList();
    // 查找插入位置
    int insertIndex = htmlContent.FindIndex(x => x.Contains(insertFlag));
    
    if (insertIndex < 0)
    {
        // 未找到插入标记时直接追加到末尾
        htmlContent.AddRange(insertLines);
    }
    else
    {
        // 从标记下一行开始一次性插入所有内容
        htmlContent.InsertRange(insertIndex + 1, insertLines);
    }
    
    // 单次写入最终文件
    File.WriteAllLines(outputPath, htmlContent);
}

3. 调用方式

直接传入预生成的insertLines调用方法即可:

Create_Driver_Report(insertLines);

兼容原有调用逻辑的方案(不推荐)

如果你一定要保留每次调用插入一行的逻辑,可以修改方法内的读取逻辑,优先读取已存在的输出文件,避免覆盖之前的内容:

private void Create_Driver_Report(string npcName)
{
    string templatePath = Get_Path("Driver_Reports.html");
    string outputPath = "drivers.html";
    string insertFlag = "<!--New Line Here-->";
    
    List<string> htmlContent;
    // 输出文件存在就读取输出文件,不存在就读取原始模板
    if (File.Exists(outputPath))
    {
        htmlContent = File.ReadAllLines(outputPath).ToList();
    }
    else
    {
        htmlContent = File.ReadAllLines(templatePath).ToList();
    }
    
    int index = htmlContent.FindIndex(x => x.Contains(insertFlag));
    htmlContent.Insert(index + 1, npcName);          
    File.WriteAllLines(outputPath, htmlContent);
}

该方案循环多少次就会执行多少次文件读写,数据量较大时性能极低,仅做兼容参考。

内容的提问来源于stack exchange,提问作者PureWare -Legends Of Gaming

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 02:24:08