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);
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());
Alternatively, if you wish to retain the previous CSV data, you can use File.AppendAllText() instead of File.WriteAllText():
File.AppendAllText(filePath, csv.ToString());
To improve code readability, C# 6.0 introduces string interpolation, allowing you to write:
string newLine = $"{first},{second}";
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!