2012-04-10 8 views
5

Usandocómo ir a nueva línea en un documento de texto utilizando VB.Net

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

¿Cómo hago la segunda línea de texto aparece debajo de la primera, como si pulsa la tecla Intro? Hacerlo de esta manera simplemente coloca la segunda línea justo al lado de la primera línea.

Respuesta

7

Usando Environment.NewLine

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

O puede utilizar el 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 
2

Tal vez:

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

vbCrLf es una constante para una nueva línea.

3

si usted tiene muchos de esto exige Es mucho mejor utilizar un 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()) 

Si tiene muchas cadenas para escribir, entonces puede envolver todo en un método.

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 
+0

Eso significa trabajar con la cadena completa en la memoria, dependiendo del tamaño, que puede ser un problema. – Magnus

+0

@Magnus sí, pero podría manejarse fácilmente con algunas llamadas intermedias a AppendAllText. Ver mi respuesta actualizada – Steve

Cuestiones relacionadas