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"));
}
}
}
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.
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With