志在指尖
用双手敲打未来

C#根据流下载文件

C#从服务器下载文件能够运用下面4个办法:TransmitFile、WriteFile、WriteFile和流办法下载文件,并保存为相应类型,办法如下:1、TransmitFile完成下载protectedvoidButton1_Click(objectsender,EventArgse)
{/*微软为Response目标供给了一个新的办法TransmitFile来处理运用Response.BinaryWrite
下载超越400mb的文件时导致Aspnet_wp.exe进程收回而无法成功下载的问题。
代码如下:*/Response.ContentType=”application/x-zip-compressed”;
Response.AddHeader(“Content-Disposition”,”attachment;filename=z.zip”);stringfilename=Server.MapPath(“DownLoad/z.zip”);
Response.TransmitFile(filename);C#
}2、WriteFile完成下载protectedvoidButton2_Click(objectsender,EventArgse)
{/*usingSystem.IO;*/stringfileName=”asd.txt”;//客户端保存的文件名stringfilePath=Server.MapPath(“DownLoad/aaa.txt”);//途径FileInfofileInfo=newFileInfo(filePath);
Response.Clear();
Response.ClearContent();
Response.ClearHeaders();
Response.AddHeader(“Content-Disposition”,”attachment;filename=”+fileName);
Response.AddHeader(“Content-Length”,fileInfo.Length.ToString());
Response.AddHeader(“Content-Transfer-Encoding”,”binary”);
Response.ContentType=”application/octet-stream”;
Response.ContentEncoding=System.Text.Encoding.GetEncoding(“gb2312″);
Response.WriteFile(fileInfo.FullName);
Response.Flush();
Response.End();
}3、WriteFile分块下载protectedvoidButton3_Click(objectsender,EventArgse)
{stringfileName=”aaa.txt”;//客户端保存的文件名stringfilePath=Server.MapPath(“DownLoad/aaa.txt”);//途径System.IO.FileInfofileInfo=newSystem.IO.FileInfo(filePath);if(fileInfo.Exists==true)
{constlongChunkSize=102400;//100K每次读取文件,只读取100K,这样能够缓解服务器的压力byte[]buffer=newbyte[ChunkSize];
Response.Clear();
System.IO.FileStreamiStream=System.IO.File.OpenRead(filePath);longdataLengthToRead=iStream.Length;//获取下载的文件总巨细Response.ContentType=”application/octet-stream”;
Response.AddHeader(“Content-Disposition”,”attachment;filename=”+HttpUtility.UrlEncode(fileName));while(dataLengthToRead>0&&Response.IsClientConnected)
{intlengthRead=iStream.Read(buffer,0,Convert.ToInt32(ChunkSize));//读取的巨细Response.OutputStream.Write(buffer,0,lengthRead);
Response.Flush();
dataLengthToRead=dataLengthToRead-lengthRead;
}
Response.Close();
}
}4、流办法下载protectedvoidButton4_Click(objectsender,EventArgse)
{stringfileName=”aaa.txt”;//客户端保存的文件名stringfilePath=Server.MapPath(“DownLoad/aaa.txt”);//途径//以字符流的形式下载文件FileStreamfs=newFileStream(filePath,FileMode.Open);byte[]bytes=newbyte[(int)fs.Length];
fs.Read(bytes,0,bytes.Length);
fs.Close();
Response.ContentType=”application/octet-stream”;//通知浏览器下载文件而不是打开Response.AddHeader(“Content-Disposition”,”attachment;filename=”+HttpUtility.UrlEncode(fileName,System.Text.Encoding.UTF8));
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();
}

未经允许不得转载:IT技术网站 » C#根据流下载文件
分享到: 更多 (0)

评论 抢沙发

评论前必须登录!

 

志在指尖 用双手敲打未来

登录/注册IT技术大全

热门IT技术

C#基础入门   SQL server数据库   系统SEO学习教程   WordPress小技巧   WordPress插件   脚本与源码下载