c# - 如何在不加载整个文件的情况下将标题行添加到 CSV?

标签 c#

我有一个控制台应用程序,我想在 CSV 文件中添加一个标题行,而不将数据加载到应用程序中。我需要什么代码来做到这一点,但也只检查第一行以查看标题是否已经存在,如果不存在则不添加标题行?我已经尝试了几种方法来做到这一点,但找不到一种方法来编码这个而不加载整个文件以检查它是否存在然后添加标题行。

最佳答案

您可以使用 StreamReaderStreamWriter 来最小化内存使用量。

我的建议是逐行读取csv文件,如果需要加header,写入临时文件。在内存方面,它是高效的。

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);
}

关于c# - 如何在不加载整个文件的情况下将标题行添加到 CSV?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43726825/

相关文章:

c# - 位掩码枚举的通用单标志枚举

c# - 对未知列使用特定的 DataTemplate

c# - 使用 Windows 技术检测复制、粘贴、打印系统命令?

c# - 如何将 JsonPatchDocument 作为发布对象中的属性传递?

c# - 更新大量数据时重复键值错误

c# - 从C#(WPF)程序向putty.exe实例发送命令

c# - 在 Windows Phone 7 应用程序的 c# 中将字符串转换为图像

c# - Unity防止点击1s

c# - System.Exception 是否有内置的抛出时间戳?

c# - C#去除列表中重复项的方法