【问题标题】:Foreach Loop File.Readlines displays nothingForeach 循环 File.Readlines 不显示任何内容
【发布时间】:2013-03-01 22:48:17
【问题描述】:

我有一个 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);
                }
            }
        }
    }
}

文本文件以制表符分隔,格式如下:

芝加哥 IL ORD 奥黑尔国际

【问题讨论】:

  • Console.WriteLine 在 Web 表单中?它可以在控制台应用程序中使用吗?
  • 您是否产生了错误?抛出一个 try/catch。
  • 我正在尝试在网络表单中执行此操作。有没有一种简单的方法可以做到这一点?我很难在网上找到文档。
  • 此外,没有任何地方定义了按钮单击处理程序。 WebForms 不做Main。你有一些阅读要做。
  • 将“Main”更改为“Page_Load”,将“Console.WriteLine”更改为“Response.Write”,您应该会看到一些东西。但你确实需要做一些研究:)

标签: c# foreach readlines


【解决方案1】:

既然是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);
         }
     }
}

由于是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();

在 aspx 中:

<asp:Label runat="server" id="lblAirportCodes"/>

【讨论】:

  • 是否有办法将线条动态添加到标签中?标签{1}.(line) 而不是 Response.Write(line);?
  • 这将添加 label1:Chicago IL ORD O'Hare International 我的意思是现有的 WebControl 标签。感谢您的帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多