How to split lines from a Windows text file (split / r / n)

My question is pretty simple. I need to get all text strings from a windows text file. All lines are separated by \ r \ n. I use String.Split, but this is not cool, because it separates with only β€œone character”, leaving an empty string that I need to remove using the 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 useless here because GetFromSomeWhere is actually RegEx, so after this file I don't have a file.

+6
string c #
source share
4 answers

You can use this String.Split overload , 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 a file path, it is much easier to use File.ReadAllLines :

 string[] lines = File.ReadAllLines(filePath); 
+15
source share

String.Split accepts a string (for example, "\ r \ n"). Not just a chararray.

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

It may be easier for you to simply use File.ReadAllLines () or File.ReadLines ()

+4
source share

you can use an extension method similar to the one below, and then your code will look like this:

  var lines = operationText.ReadAsLines(); 

Implementation of the extension method:

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

I guess this is not as strong as the split option, which is usually very effective, but if that is not a problem ...

+3
source share

All Articles