Question Text file how to replace CRLF to LF?

raysefo

Well-known member
Joined
Jul 21, 2010
Messages
207
Programming Experience
Beginner
Hi,

I m trying to read a text file, make some changes and write to another file. But the problem is, when I create file like below;

...
Dim e1 As Encoding = Encoding.GetEncoding("ISO-8859-9")

'Pass the file path and the file name to the StreamWriter constructor.
objStreamWriter = New StreamWriter("d:\DRAWPROGRAM\Draw_Program.txt", False, e1)
...

There are CRLF at the end of lines. Is there a way to replace those with LF?

I tried like below but nothings changed:
...
Const cr As String = vbCrLf
Const lf As String = vbLf
...
Dim str As String = Regex.Replace(replaced, cr, lf)
'Write a line of text.
objStreamWriter.WriteLine(str)
 
Read the whole file into a String, call Replace on that String and then write it back out to the file.
VB.NET:
Dim text As String = IO.File.ReadAllText(filePath)

text = text.Replace(ControlChars.CrLf, ControlChars.Lf)
IO.File.WriteAllText(filePath, text)
You could even condense all that into a single line if you wanted to. Note that you are able to pass an Encoding object to ReadAllText and WriteAllText if desired.
 
Back
Top