Tuesday, May 13, 2014

Loading a .TXT file into a Label using C# in ASP.NET

Some times its very important to get and show data from an external file like .txt file. So in this example I will show you how to get the data of a .txt file in a label or a text box in ASP.NET using C#.

Create a new project and add a web form. In the App_Data folder create a txt file and put some data into it. We will get the value of from that txt file.

On the page load event of your web form write the following code.


if (!this.IsPostBack)
{
    using (StreamReader stRead = 
               new StreamReader(Server.MapPath("~/App_Data/file.txt")))
    {
        int i = 0;
        string name = string.Empty;
        string valueFromtoEnd = string.Empty;
 
        while (!stRead.EndOfStream)
        {
            if (i > 2 && i <= 4)
            {
                valueFromtoEnd += stRead.ReadLine();
            }
            else
            {
                Label1.Text = Label1.Text + stRead.ReadLine() + "<br />";
            }
            i++;
            if (i > 4)
            {
                break;
            }
        }
    }
}


It will show the text as in the .txt file.
If you want to show it in a text box just change the label into a text box.

Download the full source code here.

0 comments:

Post a Comment

Popular Posts

Pageviews