vb.net 如何一次将多行文本写入文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16048895/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 13:17:29  来源:igfitidea点击:

How would I write multiple lines of text to a file all at once?

.netvb.netfile-iomultilinestreamwriter

提问by user2288508

I need to write lots of text to a file at once, but It has to be formatted in a specific way and not all in one line.

我需要一次将大量文本写入一个文件,但它必须以特定方式格式化,而不是全部在一行中。

The code I have is:

我的代码是:

  If System.IO.File.Exists(filepath) Then
        Using reader As StreamReader = New StreamReader(filepath)
            sLine = reader.ReadToEnd
        End Using

        Using writer As StreamWriter = New StreamWriter(filepath)
            writer.Write("[HealthBarSettings]
            MaxHealthTicks = 50
            MaxHealthMicroTicks = 100
            DefaultHealthPerMicroTick = 50
            DefaultHealthPerTick = 200
            DefaultHealthPerMegaTick = 1000

            TickAlpha = 200
            MicroTickAlpha = 140
            MicroTickHeight = 0.5
            MegaTickAlpha = 255
            TickThickness = 1.0
            MicroTickThickness = 1.0
            MegaTickThickness = 2.0

            UseCompression = 1
            GoTransparent = 1

            [GeneralDataHero]()
            FadeTimerForHealthBar = 2.0
            ZeroHealthAlpha = 225
            FullHealthAlpha = 200
            DefaultChampionCollisionRadius = 65.0")

        End Using
        MsgBox("File Written")
    Else
        MsgBox("File does not exist")
    End If

But that doesn't work because it won't use all of the text and just use the "[HealthBarSettings]" and automatically end the quote after that.

但这不起作用,因为它不会使用所有文本,只使用“[HealthBarSettings]”并在此之后自动结束引用。

回答by Cody Gray

VB.NET does not support multi-line string literals. You have to indicate the line breaks yourself manually.

VB.NET 不支持多行字符串文字。您必须自己手动指示换行符。

For example:

例如:

If System.IO.File.Exists(filepath) Then
    Using reader As StreamReader = New StreamReader(filepath)
        sLine = reader.ReadToEnd
    End Using

    Using writer As StreamWriter = New StreamWriter(filepath)
        writer.Write("[HealthBarSettings]" & vbNewLine & _
        "MaxHealthTicks = 50" & vbNewLine & _
        "MaxHealthMicroTicks = 100" & vbNewLine & _
        "DefaultHealthPerMicroTick = 50" & vbNewLine & _
        "DefaultHealthPerTick = 200" & vbNewLine & _
        "DefaultHealthPerMegaTick = 1000" & vbNewLine & _
        vbNewLine & _
        "TickAlpha = 200" & vbNewLine & _
        "MicroTickAlpha = 140" & vbNewLine & _
        "MicroTickHeight = 0.5" & vbNewLine & _
        "MegaTickAlpha = 255" & vbNewLine & _
        "TickThickness = 1.0" & vbNewLine & _
        "MicroTickThickness = 1.0" & vbNewLine & _
        "MegaTickThickness = 2.0" & vbNewLine & _
        vbNewLine & _
        "UseCompression = 1" & vbNewLine & _
        "GoTransparent = 1" & vbNewLine & _

        ' etc...

    End Using
    MsgBox("File Written")
Else
    MsgBox("File does not exist")
End If

It's much easier to do and looks a lot more sensible if you're building the string up dynamically with user preference values stored in variables, rather than hard-coding it all.

如果您使用存储在变量中的用户首选项值动态构建字符串,而不是对所有内容进行硬编码,那么这样做会容易得多并且看起来更明智。

回答by vijay

Put all your text (lines) in one array and use

将所有文本(行)放在一个数组中并使用

        var arr = new[]{ "MaxHealthTicks = 50","MaxHealthMicroTicks = 100","DefaultHealthPerMicroTick = 50",
        "DefaultHealthPerTick = 200", "DefaultHealthPerMegaTick = 1000"};

        File.WriteAllLines(@"c:/temp/test.txt", arr);

It will write all your text lines in new line with proper formatting. Text in file

它将以正确的格式在新行中写入所有文本行。 文件中的文本

回答by Dan Drews

An example of how to do this with a string builder

如何使用字符串生成器执行此操作的示例

Dim sb as new StringBuilder
sb.appendLine("Line1")
sb.appendLine("Line2")
File.writeAllLines(filePath, sb.toString())

This is a good way to do it because the string builder object is more efficient than concatenating a string repeatedly, details given Here

这是一个很好的方法,因为字符串生成器对象比重复连接字符串更有效,详细信息在此处给出

回答by Michael Parr

Cody Gray mentioned it very clearly, so i'm not sure how you managed to get an error on the last line.

科迪格雷非常清楚地提到了它,所以我不确定你是如何在最后一行得到错误的。

Remember that all you are doing is really making a long string to save. You could write the whole thing on a single line if you wanted.

请记住,您所做的只是制作一个长字符串以进行保存。如果您愿意,您可以将整件事写在一行上。

vbnewline adds a newline (clear), the & sign ready's it do add another line, and the underscore you see is used to allow the code* to be displayed on multiple lines (Optional).

vbnewline 添加一个换行符(清除),& 符号准备好了它会添加另一行,您看到的下划线用于允许代码* 显示在多行上(可选)。

The final bit of code for the writer should be.

作者的最后一段代码应该是。

..."[GeneralDataHero]()" & vbNewLine & _
"FadeTimerForHealthBar = 2.0" & vbNewLine & _
"ZeroHealthAlpha = 225" & vbNewLine & _
"FullHealthAlpha = 200" & vbnewline & _
"DefaultChampionCollisionRadius = 65.0")

End Using

The expression expected error you are getting sounds like you have ended with the & symbol, or underline character. It should end as seen above, with the last string value in "quotes" and a closing bracket.

您收到的表达式预期错误听起来像是以 & 符号或下划线字符结尾。它应该如上所示结束,最后一个字符串值在“引号”和一个右括号中。

When beginning vb.net i found it easier to add everything together into a single string, then put the string into the writer. Waste of time in the end, but can be put together a little clearer using string = string & value.

开始使用 vb.net 时,我发现将所有内容添加到一个字符串中,然后将字符串放入编写器中更容易。到底是浪费时间,不过可以用string = string & value组合起来更清晰一点。

回答by Ahmed

On similar note if you want to save a multiline text in a textbox into a file use the following code:

同样,如果要将文本框中的多行文本保存到文件中,请使用以下代码:

    Dim iText As New System.IO.StreamWriter("C:\Test.txt", True)

    For Each iLineTxt As String In Textbox1.Lines
        iText.WriteLine(iLineTxt)
    Next

    iText.Close()