- Home /
StreamWriter WriteLine + StringBuilder seems to append an empty line at the end of the file
Hello,
My save to file method appends an additional empty line at the end of the file; which creates issue when I want to re-import the data line by line. (Index out of range)
The "CSV" file already has a trailing empty line; so after it writes it has two. (using pipe '|' delimiters instead of commas ',').
Is this expected behavior?
public void SaveDialogsBackToFile() {
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.AppendLine(string.Join("|", "id", "npc", "order", "dialog", "accept", "decline", "completed"));
foreach (var dict in dictDialogs) {
Dialog d = dict.Value;
sb.AppendLine(string.Join("|", d.id, d.npc, d.order, d.dialog, d.accept, d.decline, d.completed));
}
System.IO.StreamWriter stream = System.IO.File.CreateText("Assets/Resources/"+dialogsFile+".csv");
stream.WriteLine(sb);
stream.Close();
}
Answer by PlanarBit · Jun 20, 2020 at 06:02 AM
StringBuilder.AppendLine()
, StreamWriter.WriteLine()
both append line terminator to the end. So you get an extra line.
Solutions:
use
StreamWriter.Write()
instead ofStreamWriter.WriteLine()
do
sb.Length--;
after foreach loop (to remove line terminator)
Your answer
![](https://koobas.hobune.stream/wayback/20220613001347im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Parsing a CSV load from server 1 Answer
Outputting data to CSV file from multiple lists at specific Headers in the CSV? 0 Answers
Raw data-format for read and write. 0 Answers
Unity doesn't detect txt file after build 3 Answers
parsing csv file 2 Answers