将一些嵌套文本写入.txt文件VB

时间:2012-10-28 14:06:46

标签: vb.net

我有这段代码:

      Dim FILE_NAME As String = "C:\filename.txt"

            Dim objWriter As New System.IO.StreamWriter(FILE_NAME)

            objWriter.Write(TextBox1.Text)
            objWriter.Close()

但我想做这样的事情(请注意下面的文字中的 objWriter.Write(TextBox.Text)):

      Dim FILE_NAME As String = "C:\filename.txt"

            Dim objWriter As New System.IO.StreamWriter(FILE_NAME)

            objWriter.Write("Lorem ipsum dolor sit amet, consectetur adipiscing objWriter.Write(TextBox1.Text). 
                             Duis dignissim, lacus vel tincidunt pellentesque, lacus ipsum venenatis libero, 
                             faucibus iaculis lectus diam id libero. Mauris interdum augue id lacus
                             commodo consequat. objWriter.Write(TextBox2.Text) et ligula sed sapien")

            objWriter.Close()

更新

实际输出:

Lorem ipsum dolor sit amet,consectetur adipiscing objWriter.Write(TextBox1.Text)。 Duis dignissim,lacus vel tincidunt pellentesque,lacus ipsum venenatis libero,commodo consequat。 TEST et ligula sed sapien

通缉输出(我想去了):

Lorem ipsum dolor sit amet, 
consectetur adipiscing objWriter.
Write(TextBox1.Text). 
Duis dignissim, lacus 
vel tincidunt pellentesque,
 lacus ipsum venenatis libero, 
commodo consequat. TEST et ligula sed sapien

1 个答案:

答案 0 :(得分:2)

在您当前的代码中执行此操作的最简单(但不一定是理想的)方式:

' UPDATED: Use Environment.NewLine to insert new line breaks:

Dim output As String = "" & _
        "Lorem ipsum dolor sit amet, consectetur adipiscing " & _
        Environment.NewLine & _
        TextBox1.Text & " " & _
        Environment.NewLine & _
        "Duis dignissim, lacus vel tincidunt pellentesque, lacus ipsum venenatis libero, " & _
        "commodo consequat. " & _
        Environment.NewLine & _
        TextBox2.Text + " " & _
        Environment.NewLine & _
        "et ligula sed sapien"

'You are trying to write to root of C here. May require elevated privileges.
' Try writing to your user directory, or documents folder. 
Dim FILE_NAME As String = "C:\filename.txt"
Dim objWriter As New System.IO.StreamWriter(FILE_NAME)
objWriter.Write(output)
objWriter.Close()

请注意,您可能会遇到尝试将文件直接写入C驱动器根目录的权限问题。在将目录路径更改为我的主文件夹之前,我遇到了与此代码类似的问题,除非我以管理员身份运行VS(您的用户不太可能这样做)。

那就是说,实际上你可能会问如何从文本编写器中读取文本框的内容,在这种情况下你必须想出一些方法来识别正确的插入点。但这就是你如何完成你在上面的代码中描述的具体内容。

更新:

您可能希望使用类似THIS的内容来指定输出目录和文件名。或者,当然,使用SaveFileDialog,并允许用户指定。

Dim path As String = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
Dim FILE_NAME As String = Path & "\MyNextNewFile.txt"