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

C# 读取CSV两列组合重复值计数并生成带递增序号的项目友好名称

C# 按CSV两列组合统计生成项目友好名称的修改方案

核心逻辑调整如下:

  1. 调整读写顺序:先读取CSV统计匹配的「项目名+构建版本」组合行数,再生成友好名称,最后写入新行,避免把当前待插入行计入统计
  2. 逐行拆分CSV列,仅统计和当前输入匹配的组合行数
  3. 序号按两位补零格式化,不足10的数值自动前补0

完整修改后代码

// 获取当前输入的项目名和构建版本
string currentProjectName = ProjectName_TextBox.Text.Trim();
string currentProjectBuild = ProjectBuild_TextBox.Text.Trim();
int matchCount = 0;
string logPath = @"C:\LOG.csv";

// 第一步:统计CSV中已有的相同组合行数
if (File.Exists(logPath))
{
    // using自动释放流资源,避免内存泄漏
    using (StreamReader sr = new StreamReader(logPath))
    {
        // 跳过表头行
        sr.ReadLine();
        string line;
        while ((line = sr.ReadLine()) != null)
        {
            if (string.IsNullOrWhiteSpace(line)) continue;
            // 按逗号拆分列(仅适用于字段无逗号的场景,有特殊字符建议用CsvHelper等专业库)
            string[] columns = line.Split(',');
            if (columns.Length >= 2)
            {
                string existedProject = columns[0].Trim();
                string existedBuild = columns[1].Trim();
                // 匹配到相同组合则计数+1,可根据需求去掉StringComparison参数开启大小写严格匹配
                if (existedProject.Equals(currentProjectName, StringComparison.OrdinalIgnoreCase) 
                    && existedBuild.Equals(currentProjectBuild, StringComparison.OrdinalIgnoreCase))
                {
                    matchCount++;
                }
            }
        }
    }
}

// 生成两位格式的序号
string serialNumber = (matchCount + 1).ToString("00");
// 生成最终友好名称
string friendlyName = $"{currentProjectName}_{currentProjectBuild}_{serialNumber}";

// 第二步:写入新行到CSV
bool isFileExisted = File.Exists(logPath);
using (StreamWriter sw = new StreamWriter(logPath, true, Encoding.UTF8))
{
    // 文件首次创建时写入表头,替换为你实际的表头内容即可
    if (!isFileExisted)
    {
        sw.WriteLine("项目名,构建版本,序号");
    }
    sw.WriteLine($"{currentProjectName},{currentProjectBuild},{serialNumber}");
}

注意事项

  • 上述实现默认CSV字段内没有逗号、换行符等特殊字符,如果你业务场景存在这类特殊字符,建议引入CsvHelper等专业CSV处理库避免拆分错误
  • 代码修正了原代码的拼写错误:projetc改为正确的project、FreindlyName改为FriendlyName
  • 匹配逻辑默认忽略大小写,如需严格区分大小写,删除StringComparison.OrdinalIgnoreCase参数即可

内容的提问来源于stack exchange,提问作者Jabir

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.14 01:33:04