8

My question is quite simple. I need to get all text lines from Windows text file. All lines are separated by \r\n symbols. I use String.Split, but its not cool, because it only splits 'by one symbol' leaving empty string that I need to remove with options flag. Is there a better way?

My implementation

string wholefile = GetFromSomeWhere();

// now parsing
string[] lines = operationtext.Split("\r\n".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);

// ok now I have lines array

UPDATE

File.ReadAllXXX is of no use here coz GetFromSomeWhere is actually RegEx, so I've no file after this point.

1
  • definitely check out this proposal. It's almost there, just needs a little more support :) Commented Jan 17, 2011 at 22:15

4 Answers 4

17

You can use this overload of String.Split, which takes an array of strings that can serve as delimiters:

string[] lines = operationtext.Split(new[] { Environment.NewLine },  
                                     StringSplitOptions.RemoveEmptyEntries);

Of course, if you already have the file-path, it's much simpler to use File.ReadAllLines:

string[] lines = File.ReadAllLines(filePath);
Sign up to request clarification or add additional context in comments.

4 Comments

Cannot use, but what if I see in Reflector what it does
@Captain Comic: To answer your question, on .NET 3.5, I can see that File.ReadAllLines uses a StreamReader to read the file line by line, loading each line into an ArrayList. It then turns this into a string-array with the ArrayList.ToArray method.
@Captain Comic: You say "cannot use" without explaining why. I don't understand why either one or both of these two methods won't do exactly what you're asking for.
Cody, I have no filepath. The regex loads the file parses it and returns me some parts from the original file. If there were String.ReadAllLines(string).
4

String.Split does accept a string (like "\r\n"). Not just a chararray.

string[] lines = wholetext.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);

Comments

4

You may find it much easier to simply use File.ReadAllLines() or File.ReadLines()

Comments

3

you could use an extension method like the one below and your code would then look like this:

    var lines = operationText.ReadAsLines();

Extension method implementation:

    public static IEnumerable<string> ReadAsLines(this string text)
    {
        TextReader reader = new StringReader(text);
        while(reader.Peek() >= 0)
        {
            yield return reader.ReadLine();
        }
    }

I'm guessing it's not as performant as the split option which is usually very performant but if that's not an issue...

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.