rup*_*610 0 c# foreach readlines
我有一个foreach循环,当我点击一个按钮时,它应该显示来自txt文件的行.单击按钮时没有显示任何内容.我究竟做错了什么?
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);
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
文本文件以制表符分隔,格式如下:
芝加哥IL ORD奥黑尔国际
由于它是Web表单,因此挂起页面的Page_Load事件.但我建议通过ASP.NET页面生命周期来了解预定义的事件.
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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
由于它是Web应用程序,因此将txt文件放在App_Data文件夹中并使用Server.MapPath函数访问它.原因是路径可能与本地计算机不同,并且最终将其部署到Web服务器.
导入using System.Text;命名空间
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();
Run Code Online (Sandbox Code Playgroud)
在aspx中:
<asp:Label runat="server" id="lblAirportCodes"/>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1372 次 |
| 最近记录: |