Tuesday, March 18, 2008

C#: Handle new line characters ("\n") while saving text to file

New line charactars as observed in multi line TextBox or RichTextBox controls ("\n") often cause invalid characters to be saved in the file when it is saved. In order to appropriately handle new line characters, the following code can be used in stead of WriteLine:

FileStream fs = new FileStream(saveFileDialog1.FileName, FileMode.OpenOrCreate,FileAccess.ReadWrite);
StreamWriter sw = new StreamWriter(fs, Encoding.UTF8);
sw.Write(txtReturn.Text.Replace("\n",Environment.NewLine)); // Environment.NewLine is the real trick ;-)
sw.Dispose(); sw = null;
fs.Dispose(); fs = null;

1 comment:

  1. Thanks, Nice fix for my new line \n problem

    ReplyDelete

Please use your common sense before making a comment, and I truly appreciate your constructive criticisms.