How to jump to a new line in a text document using VB.Net

Using

File.AppendAllText("c:\mytextfile.text", "This is the first line")
File.AppendAllText("c:\mytextfile.text", "This is the second line")

How to make the second line of text first, as if I had pressed Enter? Performing this method simply puts the second line next to the first line.

+5
source share
3 answers

Using Environment.NewLine

File.AppendAllText("c:\mytextfile.text", "This is the first line")
File.AppendAllText("c:\mytextfile.text", Environment.NewLine + "This is the second line")

Or you can use StreamWriter

Using writer As new StreamWriter("mytextfile.text", true)
    writer.WriteLine("This is the first line")
    writer.WriteLine("This is the second line")
End Using
+7
source

if you have a lot of such calls. Better to use StringBuilder:

Dim sb as StringBuilder = New StringBuilder()
sb.AppendLine("This is the first line")
sb.AppendLine("This is the second line")
sb.AppendLine("This is the third line")
....
' Just one call to IO subsystem
File.AppendAllText("c:\mytextfile.text", sb.ToString()) 

If you really have many lines to write, you can wrap everything in a method.

Private Sub AddTextLine(ByVal sb As StringBuilder, ByVal line as String)
    sb.AppendLine(line)
    If sb.Length > 100000 then
        File.AppendAllText("c:\mytextfile.text", sb.ToString()) 
        sb.Length = 0
    End If        
End Sub
+3
source

May be:

File.AppendAllText("c:\mytextfile.text", "This is the first line")
File.AppendAllText("c:\mytextfile.text", vbCrLf & "This is the second line")

vbCrLf is a constant for a new line.

+2
source

All Articles