如何在file.WriteLine中使用字符串

时间:2017-04-09 17:55:57

标签: vb.net windows-applications

我试图在Visual Basic中使用file.WriteLine将一串代码插入到文本文件中,但每当我检查文本文件时,它只复制了字符串名称,而不是它的内容,这是我的代码:

文本文件将包含" printf(strc011);"而不是替换" strc011"部分与#34; Hello World!"

Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim file As System.IO.StreamWriter
        file = My.Computer.FileSystem.OpenTextFileWriter("TEST.txt", True)
        Dim strc011 As String
        strc011 = "Hello World!"
        file.WriteLine("#include<stdio.h>
                        main()
                        {
                        printf(strc011);}
        ")
        file.Close()
    End Sub
End Class

2 个答案:

答案 0 :(得分:2)

假设您正在使用VB 14 or newer,那么您将要使用String Interpolation,这是一种模板。

这是一个正确的实施:

Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim file As System.IO.StreamWriter
        file = My.Computer.FileSystem.OpenTextFileWriter("TEST.txt", True)
        Dim strc011 As String
        strc011 = "Hello World!"
        file.WriteLine($"#include<stdio.h>
                        main()
                        {
                        printf({strc011});}
        ")
        file.Close()
    End Sub
End Class

答案 1 :(得分:0)

我弄清楚了,结果我定义了&amp;以错误的方式调用字符串,这是工作代码:

Public Class Form1 Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click Dim file As System.IO.StreamWriter file = My.Computer.FileSystem.OpenTextFileWriter("TEST.txt", True) Dim strc011 As String = "Hello World!" file.WriteLine("#include<stdio.h> main() { printf(""" & strc011 & """);} ") file.Close() End Sub End Class

Dim strc011 As String =&#34; Hello World!&#34; - 用于定义字符串

&#34;&#34;&#34; &安培; strc011&amp; &#34;&#34;&#34; - 用于调用