Csvhelper: 我们可以在没有标题的现有 CSV 文件中添加新行吗?

创建于 2018-08-22  ·  4评论  ·  资料来源: JoshClose/CsvHelper

我想将一条记录附加到现有的 CSV 文件中,以便标题已经可用。 我只想将新记录附加到现有的 CVS 文件中。

以下是我的代码。
string filePath = "C:\Users\dushyant.patel\Desktop\ExportUtility\123.csv";
StreamWriter writer = new StreamWriter(filePath, true);

SharedDataModel 模型 = new SharedDataModel();
model.SrNo = "17";
model.TypeofEvidence = "视频";

var csv = new CsvWriter(writer);
var 记录 = 新列表{ 模型 };
csv.WriteRecords(记录);
writer.Close();
返回视图();

最有用的评论

我已经能够在不重复标题行的情况下附加到文件中:

// Do not include the header row if the file already exists
CsvConfiguration csvConfig = new CsvConfiguration(CultureInfo.CurrentCulture)
{
    HasHeaderRecord = !File.Exists(FileName)
};

// WARNING: This will throw an error if the file is open in Excel!
using (FileStream fileStream = new FileStream(FileName, FileMode.Append, FileAccess.Write, FileShare.ReadWrite))
{
    using (StreamWriter streamWriter = new StreamWriter(fileStream))
    {
        using (var csv = new CsvWriter(streamWriter, csvConfig))
        {
            // Append records to csv
            csv.WriteRecords(recordsToWrite);
        }
    }
}

_注意:确保以相同的方式构建recordsToWrite集合中的每条记录以避免列不匹配_

所有4条评论

有什么我可以使用的内置方法吗?

您必须读取该文件,然后再次写入。 读者和作者仅向前。 没有办法编辑文件。

您可以同时写入一个文件并写入另一个文件,然后在完成后删除旧文件。

好的。 感谢您的宝贵回应

我已经能够在不重复标题行的情况下附加到文件中:

// Do not include the header row if the file already exists
CsvConfiguration csvConfig = new CsvConfiguration(CultureInfo.CurrentCulture)
{
    HasHeaderRecord = !File.Exists(FileName)
};

// WARNING: This will throw an error if the file is open in Excel!
using (FileStream fileStream = new FileStream(FileName, FileMode.Append, FileAccess.Write, FileShare.ReadWrite))
{
    using (StreamWriter streamWriter = new StreamWriter(fileStream))
    {
        using (var csv = new CsvWriter(streamWriter, csvConfig))
        {
            // Append records to csv
            csv.WriteRecords(recordsToWrite);
        }
    }
}

_注意:确保以相同的方式构建recordsToWrite集合中的每条记录以避免列不匹配_

此页面是否有帮助?
0 / 5 - 0 等级