我一直在尝试新的东西,基本上我偶然发现了这个:http://www.homeandlearn.co.uk/csharp/csharp_s4p11.html
我的表单有一个保存选项以及多个标签。我想将所有richtextbox保存到文本文件中。但是,当我添加多个richtextbox时,它只保存底部的那个,所以我猜公式是错的?
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
string Saved_File = "";
saveFD.InitialDirectory = "C:";
saveFD.Title = "Save your file as...";
saveFD.FileName = "";
saveFD.Filter = "Text (*.txt)|*.txt|All Files(*.*)|*.*";
if (saveFD.ShowDialog() != DialogResult.Cancel)
{
Saved_File = saveFD.FileName;
richTextBox1.SaveFile(Saved_File, RichTextBoxStreamType.PlainText);
richTextBox2.SaveFile(Saved_File, RichTextBoxStreamType.PlainText);
richTextBox3.SaveFile(Saved_File, RichTextBoxStreamType.PlainText);
richTextBox53.SaveFile(Saved_File, RichTextBoxStreamType.PlainText);
}
}
在上面的示例中,它只会保存richTextBox53,为什么不保存上面所有的richTextBox?以及如何将所有这些文件保存到文本文件中?
答案 0 :(得分:1)
正如我在评论中所说,覆盖是saveFile函数中流的默认行为
所以你需要指定文件模式。
System.IO.FileStream fs =
new System.IO.FileStream(Saved_File,
System.IO.FileMode.OpenOrCreate,System.IO.FileAccess.ReadWrite);
richTextBox1.SaveFile(fs, Saved_File);
richTextBox2.SaveFile(fs, Saved_File);
richTextBox3.SaveFile(fs, Saved_File);
richTextBox53.SaveFile(fs, Saved_File);
fs.Close();
答案 1 :(得分:1)
using (StreamWriter writer = File.AppendText(saveFD.FileName))
{
richTextBox1.SaveFile(writer , RichTextBoxStreamType.PlainText);
richTextBox2.SaveFile(writer , RichTextBoxStreamType.PlainText);
richTextBox3.SaveFile(writer , RichTextBoxStreamType.PlainText);
richTextBox53.SaveFile(writer , RichTextBoxStreamType.PlainText);
}
答案 2 :(得分:0)
试试这个
string Saved_File = "";
saveFD.InitialDirectory = "C:";
saveFD.Title = "Save your file as...";
saveFD.FileName = "";
saveFD.Filter = "Text (*.txt)|*.txt|All Files(*.*)|*.*";
if (saveFD.ShowDialog() != DialogResult.Cancel)
{
Saved_File = saveFD.FileName;
RichTextBox allrtb = new RichTextBox();
// This one add new lines using the "\n" every time you add a rich text box
allrtb.AppendText(richTextBox1.Text + "\n" + richTextBox2.Text + "\n" + richTextBox3.Text+ "\n" + richTextBox53.Text );
allrtb.SaveFile(Saved_File, RichTextBoxStreamType.PlainText);
}
现在,如果你想在richtextbox之间留出空格,只需将新行(即\ n)更改为如下所示的空格:
allrtb.AppendText(richTextBox1.Text + " " + richTextBox2.Text + " " + richTextBox3.Text+ " " + richTextBox53.Text );