C# remove all new line and blank line

Tub Ntxawg Yaaj 121 Reputation points
2020-12-02T07:08:03.227+00:00

Example of Text file:

test1


Test2





Test3

Test4

Expectation: I wanted to first remove all double or more blank line and replace them with a single blank line then register the number shown on the last line as a variable.

Test1

Test2

Test3 

Test4

Here is the codes I have but am getting an error about cannot convert to string when trying to write out the double + blank lines to a single blank line.

    string path = @"C:\Users\LC\Desktop\test.txt";

    var lastline = File.ReadLines(path).Last();


    // Remove all newlines from the 'example' string variable
    lines = Regex.Replace(path, @"^\s+$[\r\n]*", @"\r\n", RegexOptions.Multiline);
    File.WriteAllLines(path, lines);

    string numbers = Regex.Replace(lastline, "[^0-9]+", string.Empty);

    MessageBox.Show(numbers);
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,196 questions
0 comments No comments
{count} votes

Accepted answer
  1. Viorel 111.7K Reputation points
    2020-12-02T10:27:40.133+00:00

    Try something like this:

    string text = File.ReadAllText( path );
    string result = Regex.Replace( text, @"(^\p{Zs}*\r\n){2,}", "\r\n", RegexOptions.Multiline );
    File.WriteAllText( path, result );
    

    Note that some text files use different line separators.

    0 comments No comments

0 additional answers

Sort by: Most helpful