Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
You can use the OpenFileDialog component to enable users to browse to a text file and load the selected file to a RichTextBox control on a Windows Form. This example instantiates OpenFileDialog at run-time.
Example
// Create an OpenFileDialog object.
OpenFileDialog openFile1 = new OpenFileDialog();
// Initialize the OpenFileDialog to look for text files.
openFile1.Filter = "Text Files|*.txt";
// Check if the user selected a file from the OpenFileDialog.
if(openFile1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
// Load the contents of the file into a RichTextBox control.
richTextBox1.LoadFile(openFile1.FileName,
RichTextBoxStreamType.PlainText);
Compiling the Code
- Copy the code into the Load_Form1 event handler. When you run the program, you will be prompted to select a text file. The contents of the selected file will be displayed in a RichTextBox control.
Robust Programming
Use the CheckFileExists, CheckPathExists, DefaultExt, Filter, Multiselect, and ValidateNames properties of the OpenFileDialog control to limit run-time errors.
See Also
Concepts
Designing a User Interface in Visual C#