1. 程式人生 > >在RichTextBox控制元件中顯示RTF格式檔案

在RichTextBox控制元件中顯示RTF格式檔案

實現效果:

  

知識運用:

    RichTextBox控制元件的LoadFile方法    //將檔案內容載入到RichTextBox控制元件中

  public void LoadFile(string path,RichTextBoxStreamType fileType)

  //屬性值:   path:字串物件, 要載入的檔名稱和位置

        fileType:RichTextBox列舉值, 用於選擇開啟檔案的型別

  和Clear方法        //清楚控制元件中的所有文字

  public void Clear()

  及OpenFileDialog物件的ShowDialog方法    //

彈出開啟檔案對話方塊

  public DialogResult ShowDialog()

實現程式碼:

        private void 開啟ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            open.Filter = "(*.rtf)|*.rtf";                                          //設定開啟檔案的過濾引數    
            if (open.ShowDialog() == DialogResult.OK)
            {
                fileName = open.FileName;                                           //儲存開啟檔案的檔名
                richTextBox1.LoadFile(fileName, RichTextBoxStreamType.RichText);    //從指定位置載入檔案
            }
        }

        private void 儲存ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (File.Exists(fileName))                                                  //如果存在檔案
            {
                richTextBox1.SaveFile(fileName, RichTextBoxStreamType.RichNoOleObjs);   //在指定路徑儲存
                MessageBox.Show("儲存成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                richTextBox1.Clear();                                                   //清空RichTextBox內容
            }
            else                                                                        //檔案不存在時
            {
                save.Filter = "(*.rtf)|*.rtf";                                          //設定檔案儲存格式
                if (save.ShowDialog() == DialogResult.OK)
                {
                    richTextBox1.SaveFile(save.FileName);                               //在指定路徑下儲存
                }
            }
        }