TEL:150-0382-3679
新闻资讯 News Center
建站知识 / 公司动态
net 生成结构化html

以前做的net生成的html。生成文件 总是一行显示完,完全打乱了原有的html结构,可读性严重降低:
源码暂时省略。
先找到一心的html生成方式,可以保持原有的html结构格式:具体源码:
using System.Text;
using System.IO;
using System.Net;
//以上为引用的命名空间
 //源码是替换掉模板中的特征字符

        string mbPath = Server.MapPath("template.htm");
        Encoding code = Encoding.GetEncoding("gb2312");
        StreamReader sr = null;
        StreamWriter sw = null;
        string str = null;

        //读取
        try
        {
            sr = new StreamReader(mbPath, code);
            str = sr.ReadToEnd();

        }
        catch (Exception ex)
        {
            throw ex;
        }
        finally
        {
            sr.Close();
        }

        //根据时间自动重命名,扩展名也可以自行修改
        string fileName = DateTime.Now.ToString("yyyyMMddHHmmss") + ".htm";
        str = str.Replace("$title$", txtTitle.Text);//替换Title
        str = str.Replace("$content$", txtContent.Text);//替换content

        //生成静态文件
        try
        {
            sw = new StreamWriter(Server.MapPath("~/") + fileName, false, code);
            sw.Write(str);
            sw.Flush();

        }
        catch (Exception ex)
        {
            throw ex;
        }
        finally
        {
            sw.Close();
            Response.Write("恭喜<a href=htm/" + fileName + " target=_blank>" + fileName + "</a>已经生成,保存在htm文件夹下!");
        }

还有一种方式  直接把某一地址的动态页面生成为html

        Encoding code = Encoding.GetEncoding("utf-8");
        StreamReader sr = null;
        StreamWriter sw = null;
        string str = null;

        //读取远程路径
        WebRequest temp = WebRequest.Create(txtUrl.Text.Trim());
        WebResponse myTemp = temp.GetResponse();
        sr = new StreamReader(myTemp.GetResponseStream(), code);
        //读取
        try
        {
            sr = new StreamReader(myTemp.GetResponseStream(), code);
            str = sr.ReadToEnd();

        }
        catch (Exception ex)
        {
            throw ex;
        }
        finally
        {
            sr.Close();
        }
        string fileName = DateTime.Now.ToString("yyyyMMddHHmmss") + ".htm";

        //写入
        try
        {
            sw = new StreamWriter(Server.MapPath("~/") + fileName, false, code);
            sw.Write(str);
            sw.Flush();

        }
        catch (Exception ex)
        {
            throw ex;
        }
        finally
        {
            sw.Close();
            Response.Write("恭喜<a href=htm/" + fileName + " target=_blank>" + fileName + "</a>已经生成,保存在htm文件夹下!");
        }

一站式全网营销,您身边的网络营销顾问,为您一对一私人定制符合您实际需求的网络营销实施方案!
24小时咨询热线:
150-0382-3679