Read text from a file stream

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.


Csharp exercises: using OpenFileDialog to select the file and read its content

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.

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Windows.Forms;

using System.IO;


namespace WindowsFormsApplication2


    public partial class Form1 : Form



        public Form1()






        private void button1_Click(object sender, EventArgs e)


            string fn="";

            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);

            string content;

            content = fr.ReadToEnd();

            fs.Close();//close the file

            return content;






This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.