public void SaveFile(Stream stream)
{
StreamWriter streamWriter = new StreamWriter(stream, this.Encoding ?? Encoding.UTF8);
// save line per line to apply the LineTerminator to all lines
// (otherwise we might save files with mixed-up line endings)
foreach (LineSegment line in Document.LineSegmentCollection) {
streamWriter.Write(Document.GetText(line.Offset, line.Length));
if (line.DelimiterLength > 0) {
char charAfterLine = Document.GetCharAt(line.Offset + line.Length);
if (charAfterLine != '\n' && charAfterLine != '\r')
throw new InvalidOperationException("The document cannot be saved because it is corrupted.");
// only save line terminator if the line has one
streamWriter.Write(document.TextEditorProperties.LineTerminator);
}
}
streamWriter.Flush();
}