51

I was following this article

And I came up with this code:

string FileName = "C:\\test.txt";

using (StreamReader sr = new StreamReader(FileName, Encoding.Default))
{
    string[] stringSeparators = new string[] { "\r\n" };
    string text = sr.ReadToEnd();
    string[] lines = text.Split(stringSeparators, StringSplitOptions.None);
    foreach (string s in lines)
    {
        Console.WriteLine(s);
    }
}

Here is the sample text:

somet interesting text\n
some text that should be in the same line\r\n
some text should be in another line

Here is the output:

somet interesting text\r\n
some text that should be in the same line\r\n
some text should be in another line\r\n

But what I want is this:

somet interesting textsome text that should be in the same line\r\n
some text should be in another line\r\n

I think I should get this result but somehow I am missing something...

5
  • 4
    Why don't you use File.ReadAllLines or File.ReadLines? Mar 4, 2014 at 23:03
  • Console.WriteLine() will add the newline automatically after each string in your array. You want to either merge the lines together BEFORE your loop, or as one answer suggested, replace the \n before you Split the text.
    – dub stylee
    Mar 4, 2014 at 23:06
  • I want to have line that specifically ends with \r\n not \n or \r.
    – skmasq
    Mar 4, 2014 at 23:08
  • 2
    The problem is not that you have \r\n and \n at the end but that you're forgetting that the lines actually contain already line-breaks. So even if you remove them you have three lines in the file. Mar 4, 2014 at 23:12
  • Are you sure the first line of the output ends with \r\n? Add this line and see if it's what you expect: Console.WriteLine("lines.Length={0}", lines.Length); Mar 4, 2014 at 23:18

9 Answers 9

71

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", ""));
1
  • Yes, Console.WriteLine() was translating \n into \r\n.
    – skmasq
    Mar 5, 2014 at 3:29
13

This worked for me.

using System.IO;

//  

    string readStr = File.ReadAllText(file.FullName);          
    string[] read = readStr.Split(new char[] {'\r','\n'},StringSplitOptions.RemoveEmptyEntries);
0
6

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);
1
  • But why should I add it?
    – Szymon
    Mar 4, 2014 at 23:19
6

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.

3

Reading the file is easier with the static File class:

// First read all the text into a single string.
string text = File.ReadAllText(FileName);

// Then split the lines at "\r\n".   
string[] stringSeparators = new string[] { "\r\n" };
string[] lines = text.Split(stringSeparators, StringSplitOptions.None);

// Finally replace lonely '\r' and '\n' by  whitespaces in each line.
foreach (string s in lines) {
    Console.WriteLine(s.Replace('\r', ' ').Replace('\n', ' '));
}

Note: The text might also contain vertical tabulators \v. Those are used by Microsoft Word as manual linebreaks.

In order to catch any possible kind of breaks, you could use regex for the replacement

Console.WriteLine(Regex.Replace(s, @"[\f\n\r\t\v]", " "));
1

This worked for me.

string stringSeparators = "\r\n";
string text = sr.ReadToEnd();
string lines = text.Replace(stringSeparators, "");
lines = lines.Replace("\\r\\n", "\r\n");
Console.WriteLine(lines);

The first replace replaces the \r\n from the text file's new lines, and the second replaces the actual \r\n text that is converted to \\r\\n when the files is read. (When the file is read \ becomes \\).

1

In Winform App(C#):

static string strFilesLoc = Path.GetFullPath(Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), @"..\..\")) + "Resources\\";
    public static string[] GetFontFamily()
            {
                var result = File.ReadAllText(strFilesLoc + "FontFamily.txt").Trim();
                string[] items = result.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
                return items;
            }

In-text file(FontFamily.txt):
Microsoft Sans Serif
9
true

0

Following code gives intended results.

string text="some interesting text\nsome text that should be in the same line\r\nsome 
text should be in another line"
var results = text.Split(new[] {"\n","\r\n"}, StringSplitOptions.None);
0

Split only works with a single character and need single quotes like '|' or '\n' but \r\n is a string so it can't be used with Split. Use Regex this instead

string[] lines=Regex.Split(str, "\r\n");

Don't forget using System.Text.RegularExpressions;

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.