明天的明天 永远的永远 未知的一切 我与你一起承担 ??

是非成败转头空 青山依旧在 几度夕阳红 。。。
  博客园  :: 首页  :: 管理

Asp.Net 2.0 防盗下载文件·············

Posted on 2007-04-26 11:05  且行且思  阅读(308)  评论(0)    收藏  举报

 public void downLoad(string path)
    {
        try
        {
            string filePath = path;
            int temp = filePath.LastIndexOf("/") + 1;
            string fileName = filePath.Substring(temp, filePath.Length - temp);
            //FileStream fileStream = new FileStream(Server.MapPath(filePath), FileMode.Open, FileAccess.Read, FileShare.Read);

            FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);

            long fileSize = fileStream.Length;
            Context.Response.ContentType = "application/octet-stream";
            Context.Response.AddHeader("Content-Disposition", "attachment; filename=\"" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8) + "\"");
            Context.Response.AddHeader("Content-Length", fileSize.ToString());
            byte[] fileBuffer = new byte[fileSize];
            fileStream.Read(fileBuffer, 0, (int)fileSize);
            fileStream.Close();
            Context.Response.BinaryWrite(fileBuffer);
            Context.Response.End();
        }
        catch
        {
            Response.Write("<script>alert('查无此资料或已被删除');</script>");
        }
    }