DownFile.cs 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Net;
  6. using System.Web;
  7. using System.IO;
  8. namespace Ant.Service.Common
  9. {
  10. /// <summary>
  11. /// 用webClient下载文件
  12. /// </summary>
  13. public partial class DownFile
  14. {
  15. #region 生成静态页面
  16. /// <summary>
  17. /// 生成静态页面
  18. /// 调用实例:
  19. /// Common.DownFile webclient = new Common.DownFile();
  20. /// string RequestVirtualUrl= "/News/ViewNews.aspx?NewsId="+Info.Id;
  21. /// string SaveVirtualPath = "~/News/" + Info.Id + ".htm";
  22. /// webclient.CreateStaticByWebClient(RequestVirtualUrl, SaveVirtualPath);
  23. /// </summary>
  24. /// <param name="VirtualRequestUrl">要请求的虚拟路径,例如: "/News/ViewNews.aspx?NewsId="+Info.Id;</param>
  25. /// <param name="SaveVirtualPath">要保存的虚拟路径,例如:"~/News/" + Info.Id + ".htm";</param>
  26. public static void CreateStaticByWebClient(string VirtualRequestUrl, string SaveVirtualPath)
  27. {
  28. WebClient wc = new WebClient();
  29. wc.Encoding = Encoding.UTF8;
  30. //通过WebClient向服务器发Get请求,把服务器返回的html内容保存到磁盘上,以后用户直接请html文件请求.
  31. string AppVirtualPath = HttpContext.Current.Request.ApplicationPath;
  32. //由于网站应用程序虚拟目录是/czcraft,而传递过来/News是正确的,
  33. //但是发布到iis上面,虚拟路径就是/,而传递过来的确实/News,路径就出错了,
  34. if (AppVirtualPath == "/")
  35. {
  36. AppVirtualPath = "";
  37. }
  38. string FilePath = HttpContext.Current.Request.Url.Scheme + "://" + HttpContext.Current.Request.Url.Authority + AppVirtualPath + VirtualRequestUrl;
  39. //保存路径
  40. string SaveFilePath = HttpContext.Current.Server.MapPath(SaveVirtualPath);
  41. //下载并保存文件
  42. wc.DownloadFile(FilePath, SaveFilePath);
  43. }
  44. #endregion
  45. }
  46. }