1. 程式人生 > >使用RichTextBox控制元件儲存檔案

使用RichTextBox控制元件儲存檔案

實習效果:

  

知識運用:

  RichTextBox控制元件的SaveFile方法  SaveFileDialog物件的ShowDialog方法

實現程式碼:

        private void 開啟RTF檔案ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            openDialog.Filter = "*.rtf|*.rtf";
            if (openDialog.ShowDialog() == DialogResult.OK)
            {
                richTextBox1.LoadFile(
                    openDialog.FileName, RichTextBoxStreamType.RichText);
            }
        }

        private void 儲存為TXT檔案ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (richTextBox1.Text != "")
            {
                saveDialog.Filter = "File Text|*.txt";
                if (saveDialog.ShowDialog() == DialogResult.OK) {
                    richTextBox1.SaveFile(
                        saveDialog.FileName,RichTextBoxStreamType.PlainText);
                    MessageBox.Show("儲存成功","提示",
                        MessageBoxButtons.OK,MessageBoxIcon.Information);
                }
            }
            else 
            {
                MessageBox.Show("請開啟檔案", "提示",
                MessageBoxButtons.OK, MessageBoxIcon.Information); 
            }
        }