Simple text reader in C#.NET - c sharp dot net
This post describes how to make a simple text reader using C# in the .net environment. The text reader will be programmed as a windows form.
In you form, start our by placing a label at the top, followed by a list box below it, followed by a second label below the list box. Name the list box, lstData and the bottom most label, lblMsg. Alternatively, you can download the zip file and run the code in your visual studio IDE instead. Be sure you have visual studio express 2008 or later, although the project should open in vs2005.
Example of form on Visual Studio IDE.

Below is the code with comments on which commands make certain things happen. Also, notice that for this program we had to bring in the system.IO namespace in order to use stream reader. This is accomplished by typing "using System.IO;" at the top of the program.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
namespace SimpleTextReader
{
public partial class frmReadTextFile : Form
{
//declare instance of StreamReader
private StreamReader inFile;
public frmReadTextFile()
{
InitializeComponent();
}
private void frmReadTextFile_Load(object sender, EventArgs e)
{
string inValue;
//remember to create a file in your c:\
//named csharp_text.txt. Fill that file
//with any lines of short text to display
//in your program
if (File.Exists(@"c:\csharp_test.txt"))
{
//This try catch statement will handle errors
//apart from the file not being present
try
{
inFile = new StreamReader(@"c:\csharp_test.txt");
//loop through text file so that you pick
//up each line in the csharp_test.txt fiel
while((inValue = inFile.ReadLine()) != null)
{
this.lstData.Items.Add(inValue);
}//end while loop
//This is optional, you can have
//the data sorted in the text box
//alphabetically. Remove this if
//the contents should be read as is
lstData.Sorted = true;
}//end try
catch(System.IO.IOException exc)
{
lblMsg.Text = exc.Message;
}
}
else
{
lblMsg.Text = "File unavailable";
label1.Text = "There is no data to display";
}
}
private void frmReadTextFile_FormClosing(object sender, FormClosingEventArgs e)
{
//the file once you exit the program
//to get this method auto generated,
//double click on the white space next
//to your FormClosing Event in the properties
//box of your visual studio IDE
try
{
inFile.Close();
}
catch
{
}
}
}
}
| Attachment | Size |
|---|---|
| SimpleTextReader.zip | 38.82 KB |
Recent comments
22 weeks 7 hours ago