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();
	}

StringBuilder.AppendLine(), StreamWriter.WriteLine() both append line terminator to the end. So you get an extra line.

Solutions:

  1. use StreamWriter.Write() instead of StreamWriter.WriteLine()
  2. do sb.Length--; after foreach loop (to remove line terminator)