首页 日志

最基本的生成静态页的方法

最基本的生成静态页的方法.(不包括添加内容到数据库中...)
小纬不笨原创不得转载. 嘿嘿嘿嘿,开个玩笑.半夜一点多啦.真不容易.
------------
//这个是DB.cs文件

public class DB
{
public bool MakeFile(string titles,string contents)
    {
        string path = HttpContext.Current.Server.MapPath("/11/Text/news/");
        //要存放生成的.html的地址
        Encoding code = Encoding.GetEncoding("gb2312");
        //读取模板文件
        string temp = HttpContext.Current.Server.MapPath("/11/Text/text.html");
        StreamReader sr = null;
        StreamWriter sw = null;
        string str = "";
        try
        {
            sr = new StreamReader(temp,code);
            str=sr.ReadToEnd();
        }
        catch(Exception exp)
        {
            HttpContext.Current.Response.Write(exp.Message);
            HttpContext.Current.Response.End();
            sr.Close();
        }
        string htmlfilename=path+DateTime.Now.ToString("yyyyMMddHHmmss")+".html";
        //替换内容
        str = str.Replace("titles",titles);
        str = str.Replace("contents",contents);

        //写文件
        try
        {
            sw = new StreamWriter(htmlfilename, false, code);
            sw.Write(str);
            sw.Flush();
        }
        catch (Exception ex)
        {
            HttpContext.Current.Response.Write(ex.Message);
            HttpContext.Current.Response.End();
        }
        finally
        {
            sw.Close();
        }
        return true;
    }
}


---------
//这个是html模板

<html >
<head>
    <title>无标题页</title>
</head>
<body>
titles <br/>
contents

</body>
</html>


---------
//这个是Default.aspx.cs文件

public partial class _Default : System.Web.UI.Page
{
    DB db = new DB();
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        string titles = this.TextBox1.Text;
        string contents = this.TextBox2.Text;
        if (db.MakeFile(titles, contents))
        {
            Response.Write("成功.");
        }
        else
        {
            Response.Write("生成Html失败.");
        }
    }
}

----------
Default.aspx文件

页面上拖两个TextBox 和一个 Buttom按钮.

posted on 2008-09-03 05:49  zly2000a  阅读(218)  评论(0编辑  收藏  举报

导航