Share via


How to: Load Files into the Windows Forms RichTextBox Control

The Windows Forms RichTextBox control can display a plain-text, Unicode plain-text, or Rich-Text-Format (RTF) file. To do so, call the LoadFile method. You can also use the LoadFile method to load data from a stream. For more information, see LoadFile(Stream, RichTextBoxStreamType).

To load a file into the RichTextBox control

  1. Determine the path of the file to be opened using the OpenFileDialog component. For an overview, see OpenFileDialog Component Overview (Windows Forms).

  2. Call the LoadFile method of the RichTextBox control, specifying the file to load and optionally a file type. In the example below, the file to load is taken from the OpenFileDialog component's FileName property. If you call the method with a file name as its only argument, the file type will be assumed to be RTF. To specify another file type, call the method with a value of the RichTextBoxStreamType enumeration as its second argument.

    In the example below, the OpenFileDialog component is shown when a button is clicked. The file selected is then opened and displayed in the RichTextBox control. This example assumes a form has a button, 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+) Place the following code in the form's constructor to register the event handler.

    this.btnOpenFile.Click += new System.EventHandler(this. btnOpenFile_Click);
    
    this->btnOpenFile->Click += gcnew 
       System::EventHandler(this, &Form1::btnOpenFile_Click);
    
    Security noteSecurity Note:

    To run this process, your assembly may require a privilege level granted by the System.Security.Permissions.FileIOPermission class. If you are running in a partial-trust context, the process might throw an exception because of insufficient privileges. For more information, see Code Access Security Basics.

See Also

Reference

RichTextBox.LoadFile

RichTextBox

Other Resources

RichTextBox Control (Windows Forms)

Controls to Use on Windows Forms