Split text with '\r\n'
Solution 1:
The problem is not with the splitting but rather with the WriteLine
. A \n
in a string printed with WriteLine
will produce an "extra" line.
Example
var text =
"somet interesting text\n" +
"some text that should be in the same line\r\n" +
"some text should be in another line";
string[] stringSeparators = new string[] { "\r\n" };
string[] lines = text.Split(stringSeparators, StringSplitOptions.None);
Console.WriteLine("Nr. Of items in list: " + lines.Length); // 2 lines
foreach (string s in lines)
{
Console.WriteLine(s); //But will print 3 lines in total.
}
To fix the problem remove \n
before you print the string.
Console.WriteLine(s.Replace("\n", ""));
Solution 2:
This worked for me.
using System.IO;
//
string readStr = File.ReadAllText(file.FullName);
string[] read = readStr.Split(new char[] {'\r','\n'},StringSplitOptions.RemoveEmptyEntries);
Solution 3:
I think the problem is in your text file. It's probably already split into too many lines and when you read it, it "adds" additional \r
and/or \n
characters (as they exist in file). Check your what is read into text
variable.
The code below (on a local variable with your text) works fine and splits into 2 lines:
string[] stringSeparators = new string[] { "\r\n" };
string text = "somet interesting text\nsome text that should be in the same line\r\nsome text should be in another line";
string[] lines = text.Split(stringSeparators, StringSplitOptions.None);
Solution 4:
I took a more compact approach to split an input resulting from a text area into a list of string . You can use this if suits your purpose.
the problem is you cannot split by \r\n so i removed the \n beforehand and split only by \r
var serials = model.List.Replace("\n","").Split('\r').ToList<string>();
I like this approach because you can do it in just one line.