For a string variable s
:
s.Split(new string[]{Environment.NewLine},StringSplitOptions.None)
This uses your environment's definition of line endings. On Windows, line endings are CR-LF (carriage return, line feed) or in C#'s escape characters \r\n
.
This is a reliable solution, because if you recombine the lines with String.Join
, this equals your original string:
var lines = s.Split(new string[]{Environment.NewLine},StringSplitOptions.None);
var reconstituted = String.Join(Environment.NewLine,lines);
Debug.Assert(s==reconstituted);
What not to do:
StringSplitOptions.RemoveEmptyEntries
, because this will break markup such as Markdown where empty lines have syntactic purpose.new char[]{Environment.NewLine}
, because on Windows this will create one empty string element for each new line.