C#如何在文本文件中写入多行?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9236584/
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-08-09 06:29:16  来源:igfitidea点击:

C# how to write multiple lines in a text file?

c#filetextlines

提问by Ian Lundberg

I am trying to press a button that takes the text from textbox4 and textbox5 to write it to a text file. BUT when I press it again to add new info to the text file it just replaces the old text in with the new. How do I get it to write another line below the first one each time I press the button?

我正在尝试按下一个按钮,该按钮将 textbox4 和 textbox5 中的文本写入文本文件。但是当我再次按下它向文本文件添加新信息时,它只会用新文本替换旧文本。每次按下按钮时,如何让它在第一行下方写另一行?

This is the code I have so far

这是我到目前为止的代码

    private void button5_Click(object sender, EventArgs e)
    {
        try
        {
            xuidspath = @"c:\xuids.txt";
            ListViewItem lvi = new ListViewItem();
            lvi.Text = textBox4.Text;
            lvi.SubItems.Add(textBox5.Text);
            listXuid.Items.Add(lvi);
            TextWriter xuids = new StreamWriter(xuidspath);
            xuids.WriteLine(textBox4.Text + "-" + textBox5.Text);
            textBox5.Clear();
            textBox4.Clear();
            xuids.Close();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message, "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }

Any ideas?

有任何想法吗?

采纳答案by Rophuine

Open the file for append.

打开文件进行追加。

FileStream xuids = new FileStream(xuidspath, FileMode.Append);

回答by Digvijay

just use StringBuilder class and File.WriteXXX methods.

只需使用 StringBuilder 类和 File.WriteXXX 方法。

StringBuilder sb = new StringBuilder();
sb.AppendLine(textBox.Text + " " + textbox2.Text);

File.WriteAllText("c:\xuids.txt",sb.ToString();

回答by Joshua Enfield

Use an overload:

使用重载:

public StreamWriter(string path, bool append);

i.e

IE

TextWriter xuids = new StreamWriter(xuidspath,true);

回答by Gilles

Change:

改变:

TextWriter xuids = new StreamWriter(xuidspath);

To:

到:

TextWriter xuids = new StreamWriter(xuidspath, true);

The second parameter is append. From MSDN (http://msdn.microsoft.com/en-us/library/36b035cb.aspx) :

第二个参数是追加。从 MSDN ( http://msdn.microsoft.com/en-us/library/36b035cb.aspx) :

Determines whether data is to be appended to the file. If the file exists and append is false, the file is overwritten. If the file exists and append is true, the data is appended to the file. Otherwise, a new file is created.

确定是否将数据附加到文件中。如果文件存在且 append 为 false,则文件将被覆盖。如果文件存在且 append 为真,则将数据附加到文件中。否则,将创建一个新文件。

回答by Aref Khandan

RichTextBox rch = new RichTextBox();
rch.Text = cmn;
foreach (string l in rch.Lines)
    strw.WriteLine(l);