最簡單的文字計數器是使用文字檔來儲存上網人數。


首先在網站根目錄中建立一個文字檔 <counter.txt>,其中只有一個數字(開始時的初值為 0),再建立下列的網頁及程式檔。


 


<Default.aspx>


<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>


 


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">


 


<html xmlns="http://www.w3.org/1999/xhtml">


<head runat="server">


    <title>未命名頁面</title>


</head>


<body>


    <form id="form1" runat="server">


    <div>


        瀏覽人數:


        <asp:Label ID="Label1" runat="server"></asp:Label>


    </div>


    </form>


</body>


</html>


 


<Default.aspx.cs>


using System;


using System.Configuration;


using System.Data;


using System.Linq;


using System.Web;


using System.Web.Security;


using System.Web.UI;


using System.Web.UI.HtmlControls;


using System.Web.UI.WebControls;


using System.Web.UI.WebControls.WebParts;


using System.Xml.Linq;


using System.IO;


 


public partial class _Default : System.Web.UI.Page


{


    string FILE_NAME;


    int counter;


    protected void Page_Load(object sender, EventArgs e)


    {


        FILE_NAME = "counter.txt";


        counter = 0;


        FILE_NAME = Page.MapPath(FILE_NAME);


        if (Session["first"] == null)


        {


            Session["first"] = "Run";


            if (File.Exists(FILE_NAME))


            {


                readNum();


                //寫入新的值


                counter = counter + 1;


                StreamWriter sw = File.CreateText(FILE_NAME);


                sw.WriteLine(counter);


                Label1.Text = Convert.ToString(counter);


                sw.Close();


            }


        }


        else


        {


            if (File.Exists(FILE_NAME))


            {


                readNum();


                Label1.Text = Convert.ToString(counter);


            }


        }


 


    }


 


    protected void readNum()


    {


        //讀出文字檔


        StreamReader sr = File.OpenText(FILE_NAME);


        String input;


        while ((input = sr.ReadLine()) != null)


        {


            counter = Convert.ToInt32(input);


        }


        sr.Close();


    }


}

arrow
arrow
    全站熱搜

    tsjeng 發表在 痞客邦 留言(0) 人氣()