Home >Backend Development >C++ >How Can I Prevent Overwriting When Writing Multiple Rows to a CSV File in C#?

How Can I Prevent Overwriting When Writing Multiple Rows to a CSV File in C#?

Susan Sarandon
Susan SarandonOriginal
2025-01-23 02:57:10770browse

How Can I Prevent Overwriting When Writing Multiple Rows to a CSV File in C#?

Writing data to CSV file in C#: Line-by-line method

In C#, you can write data to a CSV file line by line. Suppose you need to write multiple rows of data to a file using a loop. However, you run into a problem where only the last row is written and overwrites the previous rows.

To resolve this issue, please follow these methods:

  1. Use StringBuilder: Instead of writing directly to the file for each line, accumulate the line data into a StringBuilder. This prevents unnecessary write operations to the file.
  2. Format rows: Use string formatting to create row data in the format ",".
  3. Append to StringBuilder: Append each row of formatted data to a StringBuilder using AppendLine to keep track of all rows.
  4. Write the file in one go: After the loop ends, use File.WriteAllText or File.AppendAllText to write the contents of the StringBuilder to the file, depending on whether you want to overwrite or append to the existing data data.

Using this approach, your code might look like this:

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

// 循环遍历数据行
string first = reader[0].ToString();
string second = image.ToString();
string newLine = $"{first},{second}";
csv.AppendLine(newLine);

// 循环结束后写入文件
File.WriteAllText(filePath, csv.ToString());</code>

By leveraging StringBuilder and lazy writing, you can effectively write all rows of data to a CSV file without overwriting.

The above is the detailed content of How Can I Prevent Overwriting When Writing Multiple Rows 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