日期:2014-05-17 浏览次数:20425 次
public static void TransferFile(string filepath) { // StreamWriter sw = new StreamWriter(@"E:/NDadmin/ndfile/2.txt", true, Encoding.UTF8); try { FileStream filestream = new FileStream(filepath, FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read); // sw.WriteLine("文件完成读取"); long filesize = filestream.Length; // sw.WriteLine("查询大小完成"); //让客户端浏览器正确识别这个文件的类型和文件大小 string filename = System.IO.Path.GetFileName(filepath).ToLower(); // sw.WriteLine("识别大小完成"); HttpContext.Current.Response.ContentType = "application/octet-stream"; // sw.WriteLine("制定类型完成"); HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=\"" + HttpUtility.UrlEncode(filename, System.Text.Encoding.UTF8) + "\";"); // sw.WriteLine("文件位置制定完成"); HttpContext.Current.Response.AddHeader("Content-Length", filesize.ToString()); //sw.WriteLine("长度制定完成"); //将文件中的数据发送到客户端 byte[] filebuffer = new byte[filesize]; //sw.WriteLine("获取文件数据"); filestream.Read(filebuffer, 0, (int)filesize); //sw.WriteLine("发送ING"); HttpContext.Current.Response.BinaryWrite(filebuffer); //sw.WriteLine("发送完成"); filestream.Close(); //sw.WriteLine("释放"); } catch (Exception ex) { HttpContext.Current.Response.Write(ex.Message); throw ex; //sw.WriteLine("报错了!" + ex.Message); //sw.WriteLine("报错了!" + ex.TargetSite); } finally { // sw.Flush(); //sw.Close(); } }