Exercise: Write a simple GUI program in C# to allow a user to select a text file from local machine and place the content of the text file in a RichTextBox.
Solution: To run the code solution for this exercise, you will need to create a project(Window Form Applications) in Visual Studio. The controls/components to be placed on your form are Button, RichTextBox, and OpenFileDialogBox.
public partial class Form1 : Form
private void button1_Click(object sender, EventArgs e)
openFileDialog1.Filter = "Text files (*.txt)|*.txt";
openFileDialog1.Multiselect = false;
fn = openFileDialog1.FileName;
richTextBox1.Text = readText(fn);
private string readText(string fn)
FileStream fs = new FileStream(fn,FileMode.Open ,FileAccess.Read);
StreamReader fr = new StreamReader(fs);
content = fr.ReadToEnd();
fs.Close();//close the file
This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages: