保存多个richtextbox使用

本文关键字:使用 richtextbox 保存 | 更新日期: 2023-09-27 18:08:57

我一直在尝试新的东西,基本上我偶然发现这个: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 ?如何将它们保存到一个文本文件中呢?

保存多个richtextbox使用

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);
}

正如我在评论中所说,重写是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();

试试这个

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