将RichTextBox的内容保存到.txt文件

时间:2017-02-07 18:28:04

标签: c# visual-studio

如何获取RichTextBox的内容并将其保存到文件中?我正在尝试下面的代码,但是我收到以下错误:

Error

private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
    Stream myStream;

    if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
    {
        if ((myStream = openFileDialog1.OpenFile()) != null)
        {
            string filename = openFileDialog1.FileName;
            string readfiletext = File.ReadAllText(filename);
            TabPage tp = new TabPage(filename); 
            RichTextBox rtb = new RichTextBox();
            WebBrowser wb = new WebBrowser();

            TableLayoutPanel tlp = new TableLayoutPanel();
            tlp.Dock = DockStyle.Fill;
            tlp.RowCount = 0;
            tlp.ColumnCount = 2;
            tlp.AutoSize = true;
            ColumnStyle cs = new ColumnStyle(SizeType.Percent, 50);
            tlp.ColumnStyles.Add(cs);
            tlp.Controls.Add(wb);
            ColumnStyle cs1 = new ColumnStyle(SizeType.Percent, 50);
            tlp.ColumnStyles.Add(cs1);
            tlp.Controls.Add(rtb);

            wb.Dock = DockStyle.Fill;
            rtb.Dock = DockStyle.Fill;

            tp.Controls.Add(tlp);
            tabControl1.TabPages.Add(tp);
            rtb.Text = readfiletext;
            wb.Navigate(filename);
            myStream.Close();

        }
    }
}

这个代码我用于saveToolStripMenuItem:

private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
    RichTextBox rtb = (RichTextBox)sender;
    SaveFileDialog savefile = new SaveFileDialog();
    savefile.Filter = "*HTML|*.html |PHP|*.php|all files *.* | *.*";
    if (savefile.ShowDialog() == DialogResult.OK)
    {
        rtb.SaveFile(savefile.FileName, RichTextBoxStreamType.PlainText);

    }
}

1 个答案:

答案 0 :(得分:0)

如果要将文本从[放到RichTextBox,则需要获取RTB的内容 - 而不是RTB本身。创建ToolStripMenuItem并将string值传递给string

ToolStrip

过去的任何事情 - 你可能过度思考并做得太多了。

此外 - 您收到该错误是因为您尝试将private void btnSave_Click(object sender, EventArgs e) { string sValue = rtb1.Text; toolStrip.Items.Add(sValue); } 输入到RichTextBox,这意味着您正在尝试将RTB本身设为MenuItem,而不是RTB的内容。显然不能这样做......