Question

I have a foreach loop that is supposed to display lines from a txt file when I click a button. Nothing is displaying when I click the button. What am I doing wrong?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;

namespace WebApplication1
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Main(object sender, EventArgs e)
        {
            foreach (string line in File.ReadLines(@"C:\Users\Matt\Desktop\AirportCodes2.txt"))
            {
                if (line.Contains("Chicago"))
                {
                    Console.WriteLine(line);
                }
            }
        }
    }
}

Text file is tab delimited, formatted like this:

Chicago IL ORD O'Hare International

Was it helpful?

Solution

Since it is web form, hook up Page_Load event of the page. But I recommend to go through ASP.NET page life cycle to understand pre-defined events.

 protected void Page_Load(object sender, EventArgs e)
 {
     foreach (string line in File.ReadLines(@"C:\Users\Matt\Desktop\AirportCodes2.txt"))
     {
         if (line.Contains("Chicago"))
         {
                 Response.Write(line);
         }
     }
}

Since it is web application, place the txt file in App_Data folder and access it using Server.MapPath function. Reason being that the path might be different from the local machine and when you finally deploy it to web server.

Import using System.Text; namespace

 StringBuilder result = new StringBuilder();
 int i = 0;
 foreach (string line in File.ReadLines(Server.MapPath("~/App_Data/AirportCodes2.txt")))
 {
       if (line.Contains("Chicago"))
       { 
           i = i + 1;
           result.Append((string.Format("label{0}:{1}",i,line));
           result.Append("<br/>");
       }
}
lblAirportCodes = result.ToString();

In aspx:

<asp:Label runat="server" id="lblAirportCodes"/>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top