문제

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

도움이 되었습니까?

해결책

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"/>
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top