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

如何在C#中将List<int>链追加写入CSV文件?

整数列表追加写入CSV文件的实现方案

需求概述

需要将整数列表写入CSV文件,每次新增链码时追加到文件末尾,每行对应一个完整的链码序列:

  • 初始链码[3,3,3,1,5,2]写入后,CSV为单行333152
  • 新增链码[3,2,3,1]后,CSV追加一行3231

完整实现代码

using System.IO;
using System.Linq;
using System.Collections.Generic;
using UnityEngine;

public void ExportCsv(List<int> chain, string _path = null)
{
    // 确定文件存储路径,默认使用Unity持久化目录
    string basePath = _path ?? UnityEngine.Application.persistentDataPath;
    string filePath = Path.Combine(basePath, "output.csv");

    // 将整数列表拼接为连续字符串(符合示例格式)
    string chainLine = string.Concat(chain.Select(num => num.ToString()));

    // 以追加模式写入文件,自动换行
    using (StreamWriter sw = new StreamWriter(filePath, append: true))
    {
        sw.WriteLine(chainLine);
    }
}

核心修改说明

  • 路径安全拼接:用Path.Combine替代手动拼接路径,避免因操作系统斜杠差异导致的路径错误
  • 格式匹配:替换原代码的逗号分隔逻辑,改用string.Concat生成无分隔符的连续数字串,匹配示例要求
  • 追加写入逻辑:StreamWriter构造函数传入append: true,确保新内容追加到文件末尾而非覆盖原有数据
  • 资源自动释放:using语句会自动释放文件流资源,避免文件被长期占用无法操作

效果验证

  • 首次执行后,output.csv内容:

333152

  • 新增链码执行后,output.csv内容:

333152
3231

内容的提问来源于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.18 06:10:18