If you just want the first line of the line, you can do this:
static string GetFirstLine(string text) { using (var reader = new StringReader(text)) { return reader.ReadLine(); } }
The StringReader class deals with various line break scripts for you. From the MSDN documentation :
A line is defined as a sequence of characters followed by a line ("\ n"), carriage return ("\ r"), or carriage return immediately along the line ("\ r \ n").
Of course, if you don't want the overhead of creating a new StringReader object (although I doubt it is big), you can implement something similar to yourself:
static string GetFirstLine(string text) { int? newlinePos = GetIndex(text, "\r") ?? GetIndex(text, "\n"); if (newlinePos.HasValue) { return text.Substring(0, newlinePos.Value); } return text; } // Not really necessary -- just a convenience method. static int? GetIndex(string text, string substr) { int index = text.IndexOf(substr); return index >= 0 ? (int?)index : null; }
Dan tao
source share