ASP.NET从网络上下载文件到服务器

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

public partial class DownYUMAFormWeb : System.Web.UI.Page
{
    /// <summary>
    /// 从网络上下载文件到服务器
    /// </summary>
    /// <param name="url"></param>
    /// <param name="filename"></param>
    /// <param name="pagecode"></param>
    protected void DownUrltoFile(string url, string filename, string pagecode)
    {
        try
        {
            //编码
            Encoding encode = Encoding.GetEncoding(pagecode);
            //请求URL
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            //设置超时(60秒)
            req.Timeout = 60000;
            this.NotFolderIsCreate(filename);
            //获取Response
            HttpWebResponse rep = (HttpWebResponse)req.GetResponse();
            //创建StreamReader与StreamWriter文件流对象
            StreamReader sr = new StreamReader(rep.GetResponseStream(), encode);
            StreamWriter sw = new StreamWriter(Server.MapPath(filename), false, encode);
            //写入内容
            sw.Write(sr.ReadToEnd());
            //清理当前缓存区,并将缓存写入文件
            sw.Flush();
            //释放相关对象资源
            sw.Close();
            sw.Dispose();
            sr.Close();
            sr.Dispose();
            Response.Write("生成文件" + filename + "成功");
        }
        catch (Exception ex)
        {
            Response.Write("生成文件" + filename + "失败,原因:" + ex.Message);
        }
    }
    /// <summary>
    /// 文件夹不存在则创建
    /// </summary>
    /// <param name="filename">文件名所在路径</param>
    protected void NotFolderIsCreate(string filename)
    {
        string fileAtDir = Server.MapPath(Path.GetDirectoryName(filename));
        if (!Directory.Exists(fileAtDir))
            Directory.CreateDirectory(fileAtDir);
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        DownUrltoFile("http://www.xxx.com/xxx.txt", "xxx.txt", "UTF-8");
    }
}