C#文件下载

 1        #region
 2         public static void ToDownload()
 3         {
 4             string downloadPath = "f:/temp/eclipse-SDK-3.6.1-win32.zip";
 5             string savename = "eclipse-3.6.1.zip";
 6             ToDownloadOrOpen(downloadPath, savename, "attachment");
 7             //ToDownloadOrOpen(downloadPath, savename, "inline");
 8         }
 9 
10         public static void ToDownloadOrOpen(string serverfilpath, string filename, string handle)
11         {
12             FileStream fileStream = new FileStream(serverfilpath, FileMode.Open);
13             long fileSize = fileStream.Length;
14             HttpContext.Current.Response.ContentType = "application/octet-stream";
15             HttpContext.Current.Response.AddHeader("Content-Disposition", handle +"; filename=\"" + UTF_FileName(filename) + "\";");
16             ////attachment --- 作为附件下载
17             ////inline --- 在线打开
18             HttpContext.Current.Response.AddHeader("Content-Length", fileSize.ToString());
19             byte[] fileBuffer = new byte[fileSize];
20             fileStream.Read(fileBuffer, 0, (int)fileSize);
21             HttpContext.Current.Response.BinaryWrite(fileBuffer);
22             fileStream.Close();
23             HttpContext.Current.Response.End();
24         }
25 
26         private static string UTF_FileName(string filename)
27         {
28             return HttpUtility.UrlEncode(filename, System.Text.Encoding.UTF8);
29         }
30         #endregion

 

posted @ 2012-12-27 18:16  宁静.致远  阅读(236)  评论(0编辑  收藏  举报