使用C#下载文件的多种方法小结
https://pythonjishu.com/bbzsoetttsxyoao/ https://blog.csdn.net/m0_58015531/article/details/131322801
https://www.cnblogs.com/ning-xiaowo/p/16792303.html
https://blog.csdn.net/yang472024191/article/details/37905749/
1. WebClient下载文件
使用WebClient下载文件是C#中最简单的方法之一。WebClient是System.Net中一个提供Web请求功能的类,可用来下载文件。
using System.Net; string url = "http://example.com/file.txt"; string filePath = @"C:\Downloads\file.txt"; using (WebClient client = new WebClient()) { client.DownloadFile(url, filePath); }
代码解释:
- 首先我们引入
System.Net
命名空间; - 然后我们定义要下载的文件的URL和要保存的本地文件路径;
- 接着使用
using
语句创建一个WebClient对象,并使用DownloadFile
方法将文件下载到本地;
WebClient的优点包括:
简单易用,适合快速开发。
支持异步操作,可以提高程序的响应速度。
支持多线程操作,可以提高下载或上传数据的速度。
WebClient的缺点包括:
不支持自定义HTTP请求头。
不支持HTTP响应的详细信息,如状态码和响应头。
不支持流式传输,只能一次性下载或上传整个文件。
2. HttpWebRequest下载文件
使用HttpWebRequest下载文件是更灵活的下载方法之一,它提供了更多的下载控制选项,例如可以设置请求头、请求超时等。支持异步多线程。可以在多线程环境下使用。
HttpWebRequest与HttpWebResponse的优点包括:
支持自定义HTTP请求头。
支持HTTP响应的详细信息,如状态码和响应头。
支持流式传输,可以分块下载或上传数据。
HttpWebRequest与HttpWebResponse的缺点包括:
使用起来非常复杂,需要手动处理HTTP请求和响应的各个部分。
示例代码:
using System.Net; using System.IO; string url = "http://example.com/file.txt"; string filePath = @"C:\Downloads\file.txt"; //建立一个web请求,返回HttpWebRequest 对象 HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) //流对象使用完后自动关闭 using (Stream streamResponse = response.GetResponseStream //文件流、流信息读到文件流中,读完关闭 using (FileStream streamFile = File.Create(filePath)) //建立字节组、并设置它的大小是多少字节 byte[] buffer = new byte[1024]; int bytesRead; //一次从流中读多少字节,并把值赋给bytesread,读完后,bytesread为0,并退出循环 while (( bytesRead = streamResponse.Read(buffer, 0, buffer.Length)) > 0) { //将指定字节的流信息写入文件流中 streamFile.Write(buffer, 0, bytesRead); }
代码解释:
- 首先我们引入
System.Net
和System.IO
命名空间; - 然后我们定义要下载的文件的URL和要保存的本地文件路径;
- 接着使用
WebRequest
的静态方法Create
创建一个HttpWebRequest
对象; - 我们使用
GetResponse
方法发送请求,并使用HttpWebResponse
对象获取响应; - 然后我们创建输入和输出流,并使用
while
循环逐个字节地读取和写入文件内容;
我们可以看到HttpWebRequest操作流程是,建立链接,客户端请求,服务端响应,关闭链接四步。
综上所述,选择使用哪个类取决于具体的需求。如果只是简单的下载或上传文件,可以使用WebClient;如果需要更多的控制和灵活性,可以使用HttpClient或HttpWebRequest与HttpWebResponse。
第二部分:
第一种:最简单的超链接方法,<a>标签的href直接指向目标文件地址,这样容易暴露地址造成盗链,这里就不说了
1、<a>标签
<a href="~/Home/download?id=1">Click to get file</a>
html:
<a href="~/Home/download?id=1">下载</a>
2、后台C#下载
(1)返回filestream
public FileStreamResult download() { string fileName = "aaa.txt";//客户端保存的文件名 string filePath = Server.MapPath("~/Document/123.txt");//路径 return File(new FileStream(filePath, FileMode.Open), "text/plain", fileName);//“text/plain”是文件MIME类型 }
(2)返回file
public FileResult download() { string filePath = Server.MapPath("~/Document/123.txt");//路径 return File(filePath, "text/plain", "1234.txt"); //1234.txt是客户端保存的名字 }
(3)TransmitFile方法
public void download() { string fileName = "aaa.txt";//客户端保存的文件名 string filePath = Server.MapPath("~/Document/123.txt");//路径 FileInfo fileinfo = new FileInfo(filePath); Response.Clear(); //清除缓冲区流中的所有内容输出 Response.ClearContent(); //清除缓冲区流中的所有内容输出 Response.ClearHeaders(); //清除缓冲区流中的所有头 Response.Buffer = true; //该值指示是否缓冲输出,并在完成处理整个响应之后将其发送 Response.AddHeader("Content-Disposition", "attachment;filename=" + fileName); Response.AddHeader("Content-Length", fileinfo.Length.ToString()); Response.AddHeader("Content-Transfer-Encoding", "binary"); Response.ContentType = "application/unknow"; //获取或设置输出流的 HTTP MIME 类型 Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312"); //获取或设置输出流的 HTTP 字符集 Response.TransmitFile(filePath); Response.End(); }
(4)Response分块下载(服务器下载文件的大小有限制,更改iis等都无法解决,感觉可能跟服务器上的安全狗有关,最后用下面的方法解决下载问题)
public void download() { string fileName = "456.zip";//客户端保存的文件名 string filePath = AppDomain.CurrentDomain.BaseDirectory.Replace("\\", "/") + "Excel/123.zip"; System.IO.FileInfo fileInfo = new System.IO.FileInfo(filePath); if (fileInfo.Exists == true) { //每次读取文件,只读取1M,这样可以缓解服务器的压力 const long ChunkSize = 1048576; byte[] buffer = new byte[ChunkSize]; Response.Clear(); //获取文件 System.IO.FileStream iStream = System.IO.File.OpenRead(filePath); //获取下载的文件总大小 long dataLengthToRead = iStream.Length;
//二进制流数据(如常见的文件下载) Response.ContentType = "application/octet-stream"; //通知浏览器下载文件而不是打开 Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName)); using (iStream)//解决文件占用问题,using 外 iStream.Dispose() 无法释放文件 { while (dataLengthToRead > 0 && Response.IsClientConnected) { int lengthRead = iStream.Read(buffer, 0, Convert.ToInt32(ChunkSize));//读取的大小 Response.OutputStream.Write(buffer, 0, lengthRead); Response.Flush(); dataLengthToRead = dataLengthToRead - lengthRead; } iStream.Dispose(); iStream.Close(); } Response.Close(); Response.End(); } }
(5)流方式下载
public void download() { string fileName = "456.zip";//客户端保存的文件名 string filePath = AppDomain.CurrentDomain.BaseDirectory.Replace("\\", "/") + "Excel/123.zip";//以字符流的形式下载文件 FileStream fs = new FileStream(filePath, FileMode.Open); byte[] bytes = new byte[(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(); }
(6)ajax方法
要重点说说这个方法,ajax返回不了文件流,所以说用ajax调用上面任意一种后台方法都要出问题,下载不了文件。
所以,只能让后台返回所需下载文件的url地址,然后调用windows.location.href。
优点:ajax可以传好几个参数(当然以json形式),传100个都无所谓。你要是用<a href="网址?参数=值"></a>的方法传100得写死。。。(公司需求,至少要传100多个参数)
缺点:支持下载exe,rar,msi等类型文件。对于txt则会直接打开,慎用!对于其他不常用的类型文件则直接报错。
html:
<input type="button" id="downloadbutton"/>
ajax:
$("#downloadbutton").click(function() { $.ajax({ type: "GET", url: "/Home/download", data: { id: "1" }, dataType: "json", success: function(result) { window.location.target = "_blank"; window.location.href = result; } }) });
后台:
public string download() { string filePath = "Document/123.xls";//路径 return filePath; }
(7)外网资源下载
string url = "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1494331750681&di=7bfc17bf6ef9b5abb02dfd2505a91e90&imgtype=0&src=http%3A%2F%2Fimg.article.pchome.net%2F00%2F35%2F62%2F34%2Fpic_lib%2Fs960x639%2FZhiwu36s960x639.jpg"; string fileName = url.Split('/')[url.Split('/').Length - 1];//客户端保存的文件名 System.Net.WebClient wc = new System.Net.WebClient(); wc.Encoding = System.Text.Encoding.GetEncoding("gb2312"); byte[] bytes = wc.DownloadData(url); Response.Clear(); //二进制流数据(如常见的文件下载) 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();
Response.ContentType 的所有类型:
$mimetypes = array(
'ez' => 'application/andrew-inset',
'hqx' => 'application/mac-binhex40',
'cpt' => 'application/mac-compactpro',
'doc' => 'application/msword',
'bin' => 'application/octet-stream',
'dms' => 'application/octet-stream',
'lha' => 'application/octet-stream',
'lzh' => 'application/octet-stream',
'exe' => 'application/octet-stream',
'class' => 'application/octet-stream',
'so' => 'application/octet-stream',
'dll' => 'application/octet-stream',
'oda' => 'application/oda',
'pdf' => 'application/pdf',
'ai' => 'application/postscript',
'eps' => 'application/postscript',
'ps' => 'application/postscript',
'smi' => 'application/smil',
'smil' => 'application/smil',
'mif' => 'application/vnd.mif',
'xls' => 'application/vnd.ms-excel',
'ppt' => 'application/vnd.ms-powerpoint',
'wbxml' => 'application/vnd.wap.wbxml',
'wmlc' => 'application/vnd.wap.wmlc',
'wmlsc' => 'application/vnd.wap.wmlscriptc',
'bcpio' => 'application/x-bcpio',
'vcd' => 'application/x-cdlink',
'pgn' => 'application/x-chess-pgn',
'cpio' => 'application/x-cpio',
'csh' => 'application/x-csh',
'dcr' => 'application/x-director',
'dir' => 'application/x-director',
'dxr' => 'application/x-director',
'dvi' => 'application/x-dvi',
'spl' => 'application/x-futuresplash',
'gtar' => 'application/x-gtar',
'hdf' => 'application/x-hdf',
'js' => 'application/x-javascript',
'skp' => 'application/x-koan',
'skd' => 'application/x-koan',
'skt' => 'application/x-koan',
'skm' => 'application/x-koan',
'latex' => 'application/x-latex',
'nc' => 'application/x-netcdf',
'cdf' => 'application/x-netcdf',
'sh' => 'application/x-sh',
'shar' => 'application/x-shar',
'swf' => 'application/x-shockwave-flash',
'sit' => 'application/x-stuffit',
'sv4cpio' => 'application/x-sv4cpio',
'sv4crc' => 'application/x-sv4crc',
'tar' => 'application/x-tar',
'tcl' => 'application/x-tcl',
'tex' => 'application/x-tex',
'texinfo' => 'application/x-texinfo',
'texi' => 'application/x-texinfo',
't' => 'application/x-troff',
'tr' => 'application/x-troff',
'roff' => 'application/x-troff',
'man' => 'application/x-troff-man',
'me' => 'application/x-troff-me',
'ms' => 'application/x-troff-ms',
'ustar' => 'application/x-ustar',
'src' => 'application/x-wais-source',
'xhtml' => 'application/xhtml+xml',
'xht' => 'application/xhtml+xml',
'zip' => 'application/zip',
'au' => 'audio/basic',
'snd' => 'audio/basic',
'mid' => 'audio/midi',
'midi' => 'audio/midi',
'kar' => 'audio/midi',
'mpga' => 'audio/mpeg',
'mp2' => 'audio/mpeg',
'mp3' => 'audio/mpeg',
'aif' => 'audio/x-aiff',
'aiff' => 'audio/x-aiff',
'aifc' => 'audio/x-aiff',
'm3u' => 'audio/x-mpegurl',
'ram' => 'audio/x-pn-realaudio',
'rm' => 'audio/x-pn-realaudio',
'rpm' => 'audio/x-pn-realaudio-plugin',
'ra' => 'audio/x-realaudio',
'wav' => 'audio/x-wav',
'pdb' => 'chemical/x-pdb',
'xyz' => 'chemical/x-xyz',
'bmp' => 'image/bmp',
'gif' => 'image/gif',
'ief' => 'image/ief',
'jpeg' => 'image/jpeg',
'jpg' => 'image/jpeg',
'jpe' => 'image/jpeg',
'png' => 'image/png',
'tiff' => 'image/tiff',
'tif' => 'image/tiff',
'djvu' => 'image/vnd.djvu',
'djv' => 'image/vnd.djvu',
'wbmp' => 'image/vnd.wap.wbmp',
'ras' => 'image/x-cmu-raster',
'pnm' => 'image/x-portable-anymap',
'pbm' => 'image/x-portable-bitmap',
'pgm' => 'image/x-portable-graymap',
'ppm' => 'image/x-portable-pixmap',
'rgb' => 'image/x-rgb',
'xbm' => 'image/x-xbitmap',
'xpm' => 'image/x-xpixmap',
'xwd' => 'image/x-xwindowdump',
'igs' => 'model/iges',
'iges' => 'model/iges',
'msh' => 'model/mesh',
'mesh' => 'model/mesh',
'silo' => 'model/mesh',
'wrl' => 'model/vrml',
'vrml' => 'model/vrml',
'css' => 'text/css',
'html' => 'text/html',
'htm' => 'text/html',
'asc' => 'text/plain',
'txt' => 'text/plain',
'rtx' => 'text/richtext',
'rtf' => 'text/rtf',
'sgml' => 'text/sgml',
'sgm' => 'text/sgml',
'tsv' => 'text/tab-separated-values',
'wml' => 'text/vnd.wap.wml',
'wmls' => 'text/vnd.wap.wmlscript',
'etx' => 'text/x-setext',
'xsl' => 'text/xml',
'xml' => 'text/xml',
'mpeg' => 'video/mpeg',
'mpg' => 'video/mpeg',
'mpe' => 'video/mpeg',
'qt' => 'video/quicktime',
'mov' => 'video/quicktime',
'mxu' => 'video/vnd.mpegurl',
'avi' => 'video/x-msvideo',
'movie' => 'video/x-sgi-movie',
'ice' => 'x-conference/x-cooltalk',
);