文件的操作(一):打开文本文件

      Computer 2007-8-26 13:52
asp.net里对文件的操作简直就是太简单了。

    先建个test.txt文件,随便在里面输入点什么内容。因为我的vs里设置的编码方式是UTF-8的,所以把txt文件另存为Unicode的编码文件,省得以后看起来是乱码。

    新建一个file.aspx文件,在它的.cs文件里引入using System.IO,然后在Page_Load里输入以下代码:

StreamReader sr = File.OpenText(Server.MapPath("test.txt"));
string str = sr.ReadLine();
while (str!=null)
{
 Response.Write(str+"<br>");
 str = sr.ReadLine();
}
sr.Close();

    其中,StreamReader sr = File.OpenText(Server.MapPath("test.txt"));是用来打开test.txt文件。

    sr.ReadLine();是读取下一行文字。

    用while可以循环地读取txt文件里的所有文字。然后显示出来。

    最后用sr.Close();来关闭文件。

    编译后运行看看,是不是把test.txt里的所有文字都显示出来了?

    完整代码如下:

using System;

using System.Collections;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Web;

using System.Web.SessionState;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.HtmlControls;

using System.IO;

 

namespace test

{

     /// <summary>

     /// file 的摘要说明。

     /// </summary>

     public class file : System.Web.UI.Page

     {

         private void Page_Load(object sender, System.EventArgs e)

         {

              if (!this.IsPostBack)

              {

                   //打开文件

                   StreamReader sr = File.OpenText(Server.MapPath("test.txt"));

                   //读取第一行文字

                   string str = sr.ReadLine();

                   //循环读取下一行文字

                   while (str!=null)

                   {

                       Response.Write(str+"<br>");

                       str = sr.ReadLine();

                   }

                   //关闭文件

                   sr.Close();

              }

         }

 

         #region Web 窗体设计器生成的代码

         override protected void OnInit(EventArgs e)

         {

              //

              // CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。

              //

              InitializeComponent();

              base.OnInit(e);

         }

        

         /// <summary>

         /// 设计器支持所需的方法 - 不要使用代码编辑器修改

         /// 此方法的内容。

         /// </summary>

         private void InitializeComponent()

         {   

              this.Load += new System.EventHandler(this.Page_Load);

 

         }

         #endregion

     }

}

标签集:TAGS:
回复Comments() 点击Count()

回复Comments

{commenttime}{commentauthor}

{CommentUrl}
{commentcontent}