6

使用

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

如何使第二行文本出现在第一行下方,就好像我按了 Enter 键一样?这样做只是将第二行放在第一行旁边。

4

3 回答 3

10

使用Environment.NewLine

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

或者您可以使用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
于 2012-04-10T19:32:05.917 回答
3

如果你有很多这样的调用,最好使用 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()) 

如果您确实有很多字符串要编写,那么您可以将所有内容包装在一个方法中。

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
于 2012-04-10T19:37:00.980 回答
2

也许:

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

vbCrLf是换行符的常数。

于 2012-04-10T19:30:26.327 回答