Home >Backend Development >C++ >How Can I Efficiently Write Data Row by Row to a CSV File in C#?

How Can I Efficiently Write Data Row by Row to a CSV File in C#?

Patricia Arquette
Patricia ArquetteOriginal
2025-01-23 03:01:09652browse

How Can I Efficiently Write Data Row by Row to a CSV File in C#?

Effective way to write CSV file line by line in C#

Writing a CSV file line by line in C# can be implemented using file I/O operations. However, be sure to consider specific specification requirements to ensure that every line is written correctly.

Initially, data is typically written manually to a CSV file using the following technique:

<code class="language-csharp">string csv = string.Format("{0},{1}\n", first, second);
File.WriteAllText(filePath, csv);</code>

However, this method overwrites previously written rows, resulting in only the last row remaining in the CSV file. In order to write all rows correctly, it is recommended to use StringBuilder objects.

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

// 使用逗号分隔值填充StringBuilder
while (reader.Read())
{
    string first = reader[0].ToString();
    string second = image.ToString();
    csv.AppendLine($"{first},{second}"); // 使用字符串插值
}

// 将整个StringBuilder写入CSV文件
File.WriteAllText(filePath, csv.ToString());</code>

Alternatively, if you wish to retain the previous CSV data, you can use File.AppendAllText() instead of File.WriteAllText():

<code class="language-csharp">File.AppendAllText(filePath, csv.ToString());</code>

To improve code readability, C# 6.0 introduces string interpolation, allowing you to write:

<code class="language-csharp">string newLine = $"{first},{second}";</code>

In summary, by using StringBuilder and File.WriteAllText() or File.AppendAllText(), you can efficiently write data to a CSV file line by line and keep all lines intact.

The above is the detailed content of How Can I Efficiently Write Data Row by Row to a CSV File in C#?. 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