您的位置:首页 > 编程语言 > ASP

asp.net生成静态html页

2007-07-03 17:19 423 查看
Index.aspx 页面 (部份参考网络)

public class index : System.Web.UI.Page
{
private void Page_Load(object sender, System.EventArgs e)
{
// 在此处放置用户代码以初始化页面
CreateHtml();
}

#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

private void CreateHtml()
{
int first;
string wd = "";
  try
  {
wd = Request.QueryString["wd"].ToString();
    first = int.Parse(Request.QueryString["first"]);
  }
  catch
  {
    throw (new Exception ("出错了!"));
  }

string path = Server.MapPath(@"html"+ wd);
//判断文件夹是否存在,不存在则创建文件夹
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path); //创建文件夹
}
//Response.Write("<script> alert('"+ path.ToString() +"'); </script>");
  string filename= path+@""+first+".htm";

  //尝试读取已有文件
  Stream s = DataBase.Create.GetFileStream (filename);
  if (s != null)//如果文件存在并且读取成功
  {
    using (s)
    {
      DataBase.Create.Stream2Stream (s, Response.OutputStream);
      Response.End ();
    }
  }
 
 
  //调用s.aspx,并且获取其输出
  StringWriter sw = new StringWriter ();
  Server.Execute ("s.aspx", sw); //s.aspx显示搜索结果
 
  string content = sw.ToString ();
 
  //输出到客户端
  Response.Write(content);
  Response.Flush();
 
  //写进文件
 
  try
  {
    using (FileStream fs = new FileStream (filename, FileMode.Create, FileAccess.Write, FileShare.Write))
    {
      using (StreamWriter streamwriter = new StreamWriter (fs, Response.ContentEncoding))
      {
        streamwriter.Write (content);
      }
    }
  }
  finally
  {
    //Response.End ();
  }
}
}

Create.cs类

public class Create
{
public Create()
{
//
// TODO: 在此处添加构造函数逻辑
//
}

public static void Stream2Stream (Stream src, Stream dst)
{
  byte[] buf = new byte[4096];
  while (true)
  {
    int c = src.Read (buf, 0, buf.Length);
    if(c==0)
      return;
    dst.Write (buf, 0, c);
  }
}

public static Stream GetFileStream(string filename)
{
  try
  {
    System.DateTime dt = File.GetLastWriteTime (filename);
    TimeSpan ts=dt - System.DateTime.Now;
    if(ts.TotalHours>1)
      return null;    //1小时后过期
    return new FileStream (filename, FileMode.Open, FileAccess.Read, FileShare.Read);
  }
  catch
  {
    return null;
  }
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: