Home >Backend Development >C++ >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:
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!