Share via


HOW TO:將檔案載入 Windows Form RichTextBox 控制項

更新:2007 年 11 月

Windows Form RichTextBox 控制項可顯示純文字、Unicode 純文字或 RTF 檔。若要這麼做,請呼叫 LoadFile 方法。您也可使用 LoadFile 方法,從資料流載入資料。如需詳細資訊,請參閱 LoadFile(Stream, RichTextBoxStreamType)

若要將檔案載入 RichTextBox 控制項

  1. 使用 OpenFileDialog 元件決定要開啟檔案的路徑。如需概觀說明,請參閱 OpenFileDialog 元件概觀 (Windows Form)

  2. 呼叫 RichTextBox 控制項的 LoadFile 方法,指定要載入的檔案並選擇性地指定檔案類型。在以下範例中,要載入的檔案是從 OpenFileDialog 元件的 FileName 屬性中取得。如果您只使用檔名當做呼叫方法的唯一引數,就會將檔案類型視為 RTF。若要指定其他檔案類型,請呼叫方法並將 RichTextBoxStreamType 列舉型別的任一值當做第二個引數。

    在以下範例中,按一下按鈕會顯示 OpenFileDialog 元件。選取的檔案會接著開啟,並在 RichTextBox 控制項中顯示。這個範例假設表單具有按鈕 btnOpenFile。

    Private Sub btnOpenFile_Click(ByVal sender As System.Object, _
       ByVal e As System.EventArgs) Handles btnOpenFile.Click
         If OpenFileDialog1.ShowDialog() = DialogResult.OK Then
           RichTextBox1.LoadFile(OpenFileDialog1.FileName, _
              RichTextBoxStreamType.RichText)
          End If
    End Sub
    
    private void btnOpenFile_Click(object sender, System.EventArgs e)
    {
       if(openFileDialog1.ShowDialog() == DialogResult.OK)
       {
         richTextBox1.LoadFile(openFileDialog1.FileName, RichTextBoxStreamType.RichText);
       }
    }
    
    private:
       void btnOpenFile_Click(System::Object ^  sender,
          System::EventArgs ^  e)
       {
          if(openFileDialog1->ShowDialog() == DialogResult::OK)
          {
             richTextBox1->LoadFile(openFileDialog1->FileName,
                RichTextBoxStreamType::RichText);
          }
       }
    

    (Visual C#、Visual C++) 將下列程式碼加入表單的建構函式以註冊事件處理常式。

    this.btnOpenFile.Click += new System.EventHandler(this. btnOpenFile_Click);
    
    this->btnOpenFile->Click += gcnew 
       System::EventHandler(this, &Form1::btnOpenFile_Click);
    
    安全性注意事項:

    若要執行這個處理序 (Process),組件可能需要 System.Security.Permissions.FileIOPermission 類別授與的權限層級。如果您正在部分信任的內容中執行動作,則會因權限不足而導致處理序擲回例外狀況。如需詳細資訊,請參閱程式碼存取安全性的基本概念

請參閱

參考

RichTextBox.LoadFile

RichTextBox

其他資源

RichTextBox 控制項 (Windows Form)

在 Windows Form 上使用的控制項