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.

  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 void btnOpenFile_Click(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);  
    System_CAPS_ICON_important.jpg Important

    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.

RichTextBox Control
Controls to Use on Windows Forms