You are developing an application that will run on several platforms, so you want to use end-of-line characters that are compatible with all platforms.
Sample code folder: Chapter 05\EndOfLine
Use the property Environment.NewLine, which returns the end-of-line characters for the current platform. For example, the following code adds a self-describing line of text to a StringBuilder and ends the line with the newline characters for the current platform:
Dim result As New System.Text.StringBuilder result.Append("Environment.NewLine").Append( _ Environment.NewLine) MsgBox(result.ToString())
The following code, which simply extends the prevous short snippet, terminates lines in 10 different ways, all with the same result in the Windows environment:
Dim result As New System.Text.StringBuilder result.Append(" vbNewLine").Append(vbNewLine) result.Append("vbCrLf").Append(vbCrLf) result.Append("vbCr").Append(vbCr) result.Append("vbLf").Append(vbLf) result.Append("Chr(13)").Append(Chr(13)) result.Append("Chr(10)").Append(Chr(10)) result.Append("Chr(13) & Chr(10)").Append(Chr(13) & Chr(10)) result.Append("Environment.NewLine").Append( _ Environment.NewLine) result.Append("ControlChars.CrLf").Append(ControlChars.CrLf) result.Append("ControlChars.NewLine").Append( _ ControlChars.NewLine) MsgBox(result.ToString( ))
Figure 5-13 shows each of these self-describing lines as displayed by the message box in the last line.
Figure 5-13. No less than 10 ways to terminate a line
Different platforms, such as Linux and Mac OS, expect different combinations of carriage-return and line-feed characters to terminate lines in documents or in displayed text. Visual Basic 2005 defines several constants you can use that explicitly combine these characters in a variety of ways. These named constants are easily identified by their "vb" prefix.
The somewhat generic vbNewLine constant provides a platform-dependent end of line, but only if an application is recompiled on each platform. Feel free to substitute any of the others if you find them more suitable.
The ControlChars.NewLine property is not a constant. Instead, this property polls the current operating system and returns the correct sequence of characters. This is your best choice when you want to compile a .NET application on one platform but run it on another.
Recipe 5.19 makes use of line endings in its adjustment of a string.