Netero Netero - 4 months ago 11x Question

VB.NET write just in the first line of file

I used over four different methods to get the text from a online text file: and overwrite it to another file.

Everything works, but I have only one problem. Everything is written in the first line and not the original format.






Here is just an example of a correct code which I'm using, but it doesn't work:

Using client As New WebClient()
Application.StartupPath & "\file.txt")
End Using


The file is using a different line-break style that is not recognized by the edit control.

There are three different types of line-break styles that are in common usage: the Windows style (CR LF), the Unix style (LF), and the classic Mac style (CR).

Windows controls like the TextBox control naturally require the Windows style, CR LF. The corresponding escape characters for C# would be \r\n; on VB, you use ControlChars.CrLf or vbCrLf. On Unix, LF (\n, or ControlChars.Lf/vbLf) is more commonly encountered. If you are getting a file from an external source, like the Internet, it probably uses Unix-style line breaks, which aren't recognized as line breaks by the Windows TextBox control. The reason it works in what you call "advanced text editors" is that they support all these different styles of line-break characters.

This is exceedingly trivial to fix. Perform a character replacement on the string, replacing LF with CR+LF, before you display it in the TextBox.

' Download the file
Dim path As String = Application.StartupPath & "\file.txt"
Using client As New WebClient()
    client.DownloadFile("", path))
End Using

' Read the file's text in as a string
Dim filedata As String = File.ReadAllText(path)

' Fix up the line endings
filedata = filedata.Replace(ControlChars.Lf, ControlChars.CrLf)

' Display the text in your TextBox
myTextBox.Text = filedata