Replace Return of Carriage and Line Feed CrLf in a Stream

1

I am reading a text file that has several CrLFs (at least 2 or more) and wishes to replace them with dashed lines or another character ...

this image is taken from notepad ++

What I have tried is this code ...

 public static string ReplaceLineFeedToDelimiter(string input, string replace)
    {
        string pattern = @"\r\n";
        Regex rx = new Regex(pattern);
        if (rx.IsMatch(input))
        {
            return rx.Replace(input, replace);
        }
        else
            return "";
    }

Where input - > line where I look for the / r / n and replace - > the character that I want to replace. in a routine where I go through the stream ...

        using (StreamWriter sWriter = new StreamWriter(MyNewFile, false, Encoding.UTF8, 1))
        {
            foreach (string line in File.ReadLines(myFile))
            {
                sWriter.WriteLine(ReplaceLineFeedToDelimiter(line, "*"));
            }

        }

This I have not been able to achieve, I do not know if the pattern of the regex is well configured ... the result is the same crlf ...

  • CrLf
  • CrLf
  • CrLf
  • CrLf

and what I need is to change those 2 or more for a "---" or another special character

    
asked by ger 14.12.2018 в 14:54
source

1 answer

0

After investigating a while longer and seeing several forums, you should read the whole stream instead of reading line by line.

the replacement is done with File.WriteAllText. In essence, perform a small method that replaces my car returns; but in a for and an IF are more than 2 / r / n

public static void ChangeCrLf(string fileArc)
    {
        string text = File.ReadAllText(fileArc);

        text = text.Replace("\r\n", "------------");

        File.WriteAllText(fileArc + ".modified", text);
    }
    
answered by 17.12.2018 / 21:27
source