Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# replace {CRLF} with {LF}

Tags:

c#

I have a text file sent from others. If I open in NotePad++ and view all the symbols, I can see both {LF} and {CRLF} work as line separator.

Example:

line1: ABC {CRLF}

line2: XYZ {LF}

Question: If I want to replace {CRLF} with {LF} and write to a new file, why the output text file cannot show separate line and the separator symbols disappear. Write just writes the line and append another line without start a new line, but the line still has {LF} in it, hasn't it? Is that because I am working in Windows system? But how the original file with both {LF} and {CR}{LF} can be viewed as two separate lines?

Code is very simple:

using (StreamReader sr = new StreamReader(@"\\...\TEST.txt"))
{
    using (StreamWriter sw = new StreamWriter(@"\\...\TEST2.txt"))
    {
        string line = "";

        while ((line = sr.ReadLine()) != null)
        {
            sw.Write(line.Replace("\r\n", "\n"));
        }
    }
}
like image 582
LONG Avatar asked Mar 10 '26 16:03

LONG


2 Answers

When you use ReadLine() you're trimming the EOL characters (CR and LF). Instead you should do one of the following ways:

string file1 = @"\\...\TEST.txt";
string file2 = @"\\...\TEST2.txt";

using (StreamReader sr = new StreamReader(file1))
{
    using (StreamWriter sw = new StreamWriter(file2))
    {
        string text = sr.ReadToEnd();        
        sw.Write(text.Replace("\r\n", "\n"));        
    }
}

Or

File.WriteAllText(file2,File.ReadAllText(file1).Replace("\r\n", "\n"));

But only if your file is not too big. Otherwise, Jim solution is the way to go.

like image 169
Magnetron Avatar answered Mar 13 '26 07:03

Magnetron


Your code doesn't work because when you call sr.Readline(), the returned string does not contain the CRLF characters. Those characters are added by WriteLine, which is essentially Write(s + Environment.NewLine).

To make your code work, change it to

while ((line = sr.ReadLine()) != null)
{
    sw.Write(line + "\n");
}

You can simplify your code with:

File.WriteAllLines("outputFileName",
   FileReadLines("inputFileName").Select(s => s + "\n");
like image 23
Jim Mischel Avatar answered Mar 13 '26 05:03

Jim Mischel