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

南笙酒味 提交于 2020-03-21 03:49:05

问题


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?

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?


回答1:


Open the file for append.

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



回答2:


just use StringBuilder class and File.WriteXXX methods.

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

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



回答3:


Use an overload:

public StreamWriter(string path, bool append);

i.e

TextWriter xuids = new StreamWriter(xuidspath,true);



回答4:


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) :

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.




回答5:


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


来源:https://stackoverflow.com/questions/9236584/c-sharp-how-to-write-multiple-lines-in-a-text-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!