Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

string

c#

.net

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.

like image 509
Captain Comic Avatar asked Nov 30 '10 11:11

Captain Comic


People also ask

How do I split a large file into smaller parts in Windows?

Open the Zip file. Open the Tools tab. Click the Split Size dropdown button and select the appropriate size for each of the parts of the split Zip file. If you choose Custom Size in the Split Size dropdown list, another small window will open and allow you to enter in a custom size specified in megabytes.

How do you break a string to the next line?

Split String at NewlineCreate a string in which two lines of text are separated by \n . You can use + to concatenate text onto the end of a string. Convert \n into an actual newline character. Although str displays on two lines, str is a 1-by-1 string containing both lines of text.


1 Answers

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);
like image 119
Ani Avatar answered Nov 15 '22 17:11

Ani