如何在不加载整个文件的情况下向 CSV 添加标题行?

2024-04-01

我有一个console application我想添加一个header row到 CSV 文件,而不将数据加载到应用程序中。我需要什么代码来执行此操作,并且仅检查第一行以查看标题是否已存在,如果不存在则不添加标题行?我尝试了几种方法来执行此操作,但无法找到一种在不加载整个文件以检查它是否存在然后添加标题行的情况下进行编码的方法。


您可以使用StreamReader and StreamWriter以最大限度地减少您的内存使用量。

我的建议是逐行读取 csv 文件并将其写入临时文件(如果需要添加标头)。从记忆角度来说,它是有效的。

private void AddHeader(string filename)
{
    string tempFilename = "temp.csv";
    bool toCopy = false;

    using (var sw = new StreamWriter(tempFilename, false))
    {
        //check if header exists
        using(var sr = new StreamReader(filename))
        {
            var line = sr.ReadLine(); // first line
            if(line != null && line != "Your Header") // check header exists
            {
                toCopy = true; // need copy temp file to your original csv

                // write your header into the temp file
                sw.WriteLine("Your Header");

                while(line != null)
                {
                    sw.WriteLine(line);
                    line = sr.ReadLine();
                }
            }
        }
    }

    if(toCopy)
        File.Copy(tempFilename, filename, true);
    File.Delete(tempFilename);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在不加载整个文件的情况下向 CSV 添加标题行? 的相关文章

随机推荐