博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

如何将ASP.NET页面保存为HTML文件

Posted on 2007-07-18 20:16  我是程序员  阅读(1253)  评论(0编辑  收藏  举报
以下为实现代码:
        /// <summary>
        /// 将文件保存为
        /// </summary>
        /// <param name="uri">请求的地址</param>
        /// <param name="queryString">查询字符串</param>
        /// <param name="targetFilePath">保存的文件路径</param>
        public static void SavePage(System.Uri uri, string queryString, string targetFilePath)
        {
            //用于保存文件的流
            System.IO.FileStream stream = null;

            //用于保存写入队对象
            System.IO.TextWriter writer = null;

            try
            {
                //创建Http请求
                HttpRequest request = new HttpRequest(uri.AbsolutePath, uri.AbsoluteUri, queryString);

                //创建保存的文件流
                stream = new System.IO.FileStream(targetFilePath, System.IO.FileMode.Create);

                //创建文件写入对象
                writer = new System.IO.StreamWriter(stream, System.Text.UTF8Encoding.UTF8);

                //创建Http反馈
                HttpResponse Response = new HttpResponse(writer);

                //创建Http上下文
                HttpContext context = new HttpContext(request, Response);

                //添加Session
                context.Items.Add("AspSession", HttpContext.Current.Session);

                //创建页面分析器
                System.Web.IHttpHandler handler = System.Web.UI.PageParser.GetCompiledPageInstance(uri.AbsolutePath,
                    HttpContext.Current.Server.MapPath(uri.AbsolutePath), context);

                //执行请求
                handler.ProcessRequest(context);

                //写入信息
                writer.Flush();

                //关闭
                writer.Close();
            }
            finally
            {
                //关闭写入器
                if (null != writer)
                {
                    writer.Dispose();
                }

                //关闭流
                if (null != stream)
                {
                    //关闭
                    stream.Dispose();
                }
            }
        }
需要注意的是Session的传递,如果不传递Session,那么与Session相关的数据就无法获得了。