TechToggle

Technology Bites Right At The Click Of Your Mouse

How To Read A Text File In C# Windows Forms Application?

Author : Muhammad Ali, Posts:30

Enthusiastic about the latest technology and blogging. Doing Computer Engineering from CEME , NUST.

Share

Last week i wrote a tutorial about storing images in database and then retrieving them through Visual Studio (C#). Now, i am going to write about reading data from text files in a C# windows forms application. It is a very simple application and even if you are not familiar with or good at C#, you can still read data from a text file stored in your hard drive, successfully.

First of all, create a text file on your desktop, you can create it anywhere in your hard drive. Name it Read Text or anything you like. Write some data in it. For instance i have written "Hi this is Ali from techtoggle.com".

Now, go to Microsoft Visual Studio (i am using the 2005 version) and create a Visual C# Windows Application and name it Read Text (you can name it anything you like). By default a windows form named Form1 will be displayed on your screen. Now just to make it more presentable, change its text to "Read Text From File" from the properties section. Using the toolbox, drag and drop a textbox and two buttons on your form. Now, from the properties section, change the text of button1 to Get Text From File and also change its name from button1 to btngettext. Similarly change the text of button2 to Exit and change its name from button2 to btnexit. This is just to avoid confusion while coding. You can also change the back color of buttons or the text box from the properties section, only if you like to. Adjust the size of the form, text box and the buttons accordingly. Now, your form should look like this :

Windows Form

Now, double click the Get Text From File button to go to the code view. Add the following directive at the top.

using System.IO;

Now, paste the following code in the function for btngettext button click event.

StreamReader objstream = new StreamReader("C:\\Users\\Muhammad Ali\\Desktop\\Read Text.txt");

textBox1.Text = objstream.ReadLine();

Note that you will have to change the path accordingly as to which location the text file from which you are trying to read text, is saved. And if you want to read all the text and not just a single line in the text file just replace ReadLine with ReadToEnd in the above code.

Now go to the design view, and double click the Exit button and paste the following code in the function for btnexit click event.

Application.Exit();

And You're done. Yes, its that simple. Run the project and you will be able to read a text file.

read text file in C#

StumbleIt | Digg | Reddit | Tweet | Facebook | Technorati | Delicious | Ping.fm | Slashdot

Post A Comment

Please note: Comment moderation is enabled and may delay your comment. There is no need to resubmit your comment.