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
Release: 2025-01-23 03:01:09
Original
651 people have browsed it

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:

string csv = string.Format("{0},{1}\n", first, second);
File.WriteAllText(filePath, csv);
Copy after login

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.

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());
Copy after login

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

File.AppendAllText(filePath, csv.ToString());
Copy after login

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

string newLine = $"{first},{second}";
Copy after login

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 of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template