Take the 2-minute tour ×

I used MyString.Split(Environment.Newline.ToCharArray()[0]) to split my string from a file into different pieces. But, every item in the array, except the first one starts with \n after I did that? I know the way that I'm splitting by newlines is kind of "cheaty" for lack of a better word, so if there is a better way of doing this, please tell me...

Here is the file... enter image description here

share|improve this question
So is each record that your expecting on a new line of a file? –  Jared Nov 18 '12 at 4:28
yeah, it's like 123 \n 123 \n 123 \n 123 –  leaf68 Nov 18 '12 at 4:32
Would you post your input file somewhere on line? Just first several lines are enough. –  Dante is not a Geek Nov 18 '12 at 4:36
add comment

2 Answers

up vote 2 down vote accepted

If you are wanting to maintain using the .Split() instead of reading a file in a line at a time you can do...

var splitResult = MyString.Split( new string[]{ System.Environment.NewLine },
    System.StringSplitOptions.RemoveEmptyEntries  );
    /* or System.StringSplitOptions.None if you want empty results as well */


The problem you were having is that in a non-unix environment the new-line "character" is actually two characters. So when you grabbed the zero index you were actually splitting on a carriage return...not the new-line character (\n).

Windows = "\r\n"

Unix = "\n"

Per http://msdn.microsoft.com/en-us/library/system.environment.newline.aspx

share|improve this answer
I wonder why it's "\r\n" instead of "\n"... thanks, this works –  leaf68 Nov 18 '12 at 4:45
Ask Microsoft :) –  Jared Nov 18 '12 at 4:53
add comment

A newline in Windows is two characters (\r and \n). The Environment.Newline.ToCharArray()[0] expression specifies only one of those characters: \r. Therefore, the other character (\n) remains as a portion of the split string.

My I suggest you read your file using something like this:

public IEnumerable<string> ReadFile(string filePath)
   using (StreamReader rdr = new StreamReader(filePath))
       string line;
          yield return line;

You might need more error handling, or to specify different file open option, or to pass a stream to method rather than the path, but the idea of using an iterator over the ReadLine() method is sound. The result is you can just use code like this:

 foreach (string line in ReadLine(" ... my file path ... "))

share|improve this answer
fyi brackets paired properly in first code block. –  Jared Nov 18 '12 at 4:55
@jared got it, thanks for spotting the typo –  Joel Coehoorn Nov 18 '12 at 4:58
np, I tried to just fix but the edit wasn't six chars... –  Jared Nov 18 '12 at 4:59
add comment

Your Answer


