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

如何在C#中向已有内容的CSV文件添加新行列表

解决C#向CSV文件添加列表行的格式问题

需求与问题场景

需要实现在C#中向已有内容的CSV文件添加新行列表的功能,现有两个数字列表:

  • List1:3 3 3 3 3 3 6 7 7 6 7 7 7 7 7 7 7 7 7 7 7 1 3 3 3 3 3 3 3 3 2 3 3 3 3 3 3 5 7 7 6 7 7 7 7 7 6 7 7 7 7 7 7 7 0 2 3 3 3 3 3 3 3 3 3 2
  • List2:3 3 5 5 7 7 7 7 6 7 7 7 7 6 7 7 7 7 6 7 7 7 7 7 1 3 2 3 3 3 3 2 3 3 3 3 3 2 3 3 3 3 2

现有代码生成的CSV格式不符合预期,期望每个列表的所有元素用逗号分隔,单独占一行。

现有代码

public void ExportCsvChain(List<DataChain> genericList)
{
    Debug.Log("masuk export csv");
    var sb = new StringBuilder();
    string _path = null;
    if (_path == null) _path = "C:/Users/";
    string fileName = _path + "/FOLDER/alif2"; 
    //var basePath = AppDomain.CurrentDomain.BaseDirectory;
    //var finalPath = Path.Combine(basePath, fileName + ".csv");
    var finalPath = Path.Combine(fileName + ".csv");
    if (!File.Exists(finalPath))
    {
        var file = File.Create(finalPath);
        file.Close();
        TextWriter sw = new StreamWriter(finalPath, true);
        sw.Write(sb.ToString());
        sw.Close();
    }
    foreach (DataChain obj in genericList)
    {
        sb = new StringBuilder();
        var line = obj.x;
        sb.Append(line.ToString() + ',');

        //sb.AppendLine(line);
        TextWriter sw = new StreamWriter(finalPath, true);
        sw.Write(sb.ToString());
        sw.Close();
    }
}

问题分析

  1. 循环中每次仅写入单个元素加逗号,导致所有元素挤在同一行,无换行
  2. 重复创建并关闭StreamWriter,效率低下且易引发IO异常
  3. Path.Combine使用错误,直接拼接文件名后缀不符合方法规范
  4. 冗余的文件创建逻辑,StreamWriter可自动创建不存在的文件

解决方案代码

适配列表集合的版本

using System.IO;
using System.Text;

public void ExportCsvChain(List<List<int>> listsToAdd)
{
    Debug.Log("masuk export csv");
    
    // 正确构建文件路径
    string basePath = "C:/Users/FOLDER";
    string fileName = "alif2.csv";
    string finalPath = Path.Combine(basePath, fileName);

    // 确保目标目录存在,避免路径错误
    Directory.CreateDirectory(basePath);

    // 使用using语句自动管理资源,无需手动关闭文件
    using (StreamWriter sw = new StreamWriter(finalPath, true))
    {
        foreach (var list in listsToAdd)
        {
            // 将列表元素拼接为逗号分隔的字符串
            string line = string.Join(",", list);
            // 写入完整一行(自动添加换行符)
            sw.WriteLine(line);
        }
    }
}

// 调用示例
// List<List<int>> dataLists = new List<List<int>> { List1, List2 };
// ExportCsvChain(dataLists);

适配原DataChain类的版本

如果你的DataChain类中obj.x对应一个完整列表,可直接修改循环逻辑:

using System.IO;
using System.Text;

public void ExportCsvChain(List<DataChain> genericList)
{
    Debug.Log("masuk export csv");
    
    string basePath = "C:/Users/FOLDER";
    string fileName = "alif2.csv";
    string finalPath = Path.Combine(basePath, fileName);

    Directory.CreateDirectory(basePath);

    using (StreamWriter sw = new StreamWriter(finalPath, true))
    {
        foreach (DataChain obj in genericList)
        {
            // 假设obj.x是List<int>类型,直接拼接成CSV行
            string line = string.Join(",", obj.x);
            sw.WriteLine(line);
        }
    }
}

关键改进点

  • 路径规范:用Path.Combine正确拼接目录与文件名,提前创建目录避免异常
  • 资源优化:using语句自动释放StreamWriter资源,避免频繁IO操作
  • 格式正确:string.Join直接生成逗号分隔的行内容,WriteLine保证每行对应一个列表
  • 逻辑简化:移除冗余的文件创建代码,简化整体流程

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 14:37:11