问题
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