Naor
Naor

Reputation: 11

C# read from text File and add to string array

I need to read from a text file and add the lines to an array, however, there is one problem. when I open the text file in notepad everything looks good

1
2
3

but if I open using notepad++, textpad, or any other text editor or even doing copy paste it will look like this

1

2
3


4

Here is the code:

using (var reader = new StreamReader(@"C:\Users\username\Desktop\Example\text1.txt".Replace("username", Environment.UserName)))
        {
            // Read the User Regex Format and add it to List
            string[] temp = reader.ReadToEnd().Split('\n');
            foreach (string s in temp)
                RegexFormat.Add(s);
        }

Upvotes: 1

Views: 574

Answers (3)

user5182794
user5182794

Reputation:

The text file probably contains windows line endings. Try using

string[] temp= reader.ReadToEnd().Split(new[] { "\r\n", "\r", "\n"},StringSplitOptions.None);

Explanation: When it comes to text files, Unix and Windows use different characters to represent a newline. Windows uses two characters called a carriage return (\r) and a newline (\n), while Unix only used a newline. Your text file probably had something weird and contained line endings in both formats. So when you opened it in notepad++ the lines with Windows endings showed an empty line.

Your old program only detected Unix line endings. By using the code I gave, the program is splitting the string whenever it sees any one of the 3 line endings: newline, carriage return, or both.

Upvotes: 2

neeKo
neeKo

Reputation: 4280

Just skip empty lines

using (var reader = ...){
    while(!reader.EndOfStream){
        var line = reader.ReadLine();
        if(!string.IsNullOrWhitespace(line))
            //add line 
    }
}

Upvotes: 0

Ashif Nataliya
Ashif Nataliya

Reputation: 922

This happens when the EOL control characters are not correct. Windows represents newlines with the carriage return and line feed. (CRLF)

In Notepad++, you can check for these characters by selecting:

View > Show Symbols > [x] Show End of Line

Verify what extra characters or bad characters you have in your file and then you need to modify your script replace or remove these characters.

Upvotes: 0

Related Questions