asp.net2.0生成静态面页方法(模板替换)

1.在页面添加以下三个命名空间:

using  System.IO;
using  System.Text;
using  System.Net;

2.在工程里面建立名"html"的文件夹 和 temp.html 的文件

temp.html    代码如下

<! DOCTYPE HTML PUBLIC  " -//W3C//DTD HTML 4.0 Transitional//EN "   >
< HTML >
< HEAD >
  
< title > $title$ </ title >
  
</ HEAD >
   
< body > $content$ </ body >
</ HTML >  

 

 

模板替换:
  string  mbPath  =  Server.MapPath( " temp.html " );
        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 " +   " .html " ;
        str 
=  str.Replace( " $title$ " , txtTitle.Text); // 替换Title
        str  =  str.Replace( " $content$ " , txtContent.Text); // 替换content

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

        }
        
catch  (Exception ex)
        {
            
throw  ex;
        }
        
finally
        {
            sw.Close();
            Response.Write(
" 恭喜<a href=html/ "   +  fileName  +   "  target=_blank> "   +  fileName  +   " </a>已经生成,保存在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 " +   " .html " ;

        
// 写入
         try
        {
            sw 
=   new  StreamWriter(Server.MapPath( " html/ " +  fileName,  false , code);
            sw.Write(str);
            sw.Flush();
        }
        
catch  (Exception ex)
        {
            
throw  ex;
        }
        
finally
        {
            sw.Close();
            Response.Write(
" 恭喜<a href=html/ "   +  fileName  +   "  target=_blank> "   +  fileName  +   " </a>已经生成,保存在html文件夹下! " );
        }

完整代码(VS2005工具  和  asp.net2.0)

http://dl2.csdn.net/down4/20070728/28110635327.rar

你可能感兴趣的:(asp.net2.0生成静态面页方法(模板替换))