Ruudster
Ruudster

Reputation: 157

How to split a text file retaining newline character

I have a textfile with lines that end with \r\n. When splitting 1 line with eg. Regex:

string[] splittedFile = Regex.Split(fileString, "\n");

Original input:

:020000040008F2\r\n

:04200000004875F02F\r\n

it will output:

:020000040008F2\r

:04200000004875F02F\r

However, I want it to be:

:020000040008F2\r\n

:04200000004875F02F\r\n

How can this be done?

Thanks!

Upvotes: 0

Views: 376

Answers (3)

Ranjith.V
Ranjith.V

Reputation: 326

You could try the following:

string[] splittedFile = fileString.Split(
    new[] {Environment.NewLine},
    StringSplitOptions.None
);

Upvotes: 1

Tim Rutter
Tim Rutter

Reputation: 4679

How about you read the file as follows:

string[] lines = File.ReadAllLines("afile.txt");

lines will not include the new line characters at all in this case, but as you don't say what you want to do next, its hard to know whether you want them there or not. Say you were to want to write the lines out again to some other file, you'd just use WriteLine from eg FileStream and the endlines would be of no concern

Upvotes: 0

Andrew Arthur
Andrew Arthur

Reputation: 1603

You can use positive look behind:

string[] splittedFile = Regex.Split(fileString, "(?<=\r\n)");

Upvotes: 1

Related Questions