Home >Backend Development >C++ >How to Write Multiple Rows to a CSV File in C# Without Overwriting Data?

How to Write Multiple Rows to a CSV File in C# Without Overwriting Data?

DDD
DDDOriginal
2025-01-23 03:11:09804browse

How to Write Multiple Rows to a CSV File in C# Without Overwriting Data?

How to write multi-line data in CSV file in C#

When writing multiple rows of data to a CSV file in C#, you often encounter the problem of retaining only the last row of data. This is because the code overwrites existing data every time it writes a new row.

To solve this problem, you can use the StringBuilder attribute as follows:

<code class="language-csharp">var csv = new StringBuilder();

// 循环遍历每一行数据
foreach (var row in dataRows)
{
    var first = row[0].ToString();
    var second = row[1].ToString();

    // 将值连接成新的一行
    var newLine = $"{first},{second}";

    // 将新的一行添加到StringBuilder
    csv.AppendLine(newLine);
}

// 将完整的CSV数据写入文件
File.WriteAllText(filePath, csv.ToString());</code>

By gathering the CSV contents into StringBuilder and writing the file in one go after all rows have been processed, you can ensure that each row is appended to the file, resulting in a properly formatted CSV file containing multiple rows.

This method is more efficient than manually appending each row because it minimizes the number of file writes, which can significantly improve performance for large data sets.

The above is the detailed content of How to Write Multiple Rows to a CSV File in C# Without Overwriting Data?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn