首页 > 编程语言 >使用C#下载文件的多种方法小结

使用C#下载文件的多种方法小结

时间:2023-09-02 15:55:09浏览次数:37  
标签:string filePath C# text image application 小结 Response 下载

https://pythonjishu.com/bbzsoetttsxyoao/

https://www.cnblogs.com/ning-xiaowo/p/16792303.html

https://blog.csdn.net/yang472024191/article/details/37905749/

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方法将文件下载到本地;

2. HttpWebRequest下载文件

使用HttpWebRequest下载文件是更灵活的下载方法之一,它提供了更多的下载控制选项,例如可以设置请求头、请求超时等。

示例代码:

using System.Net;
using System.IO;
string url = "http://example.com/file.txt"; string filePath = @"C:\Downloads\file.txt"; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) using (Stream streamResponse = response.GetResponseStream()) using (Stream streamFile = File.Create(filePath)) { byte[] buffer = new byte[1024]; int bytesRead; while ((bytesRead = streamResponse.Read(buffer, 0, buffer.Length)) > 0) { streamFile.Write(buffer, 0, bytesRead); } }

代码解释:

  • 首先我们引入System.NetSystem.IO命名空间;
  • 然后我们定义要下载的文件的URL和要保存的本地文件路径;
  • 接着使用WebRequest的静态方法Create创建一个HttpWebRequest对象;
  • 我们使用GetResponse方法发送请求,并使用HttpWebResponse对象获取响应;
  • 然后我们创建输入和输出流,并使用while循环逐个字节地读取和写入文件内容;

第一种:最简单的超链接方法,<a>标签的href直接指向目标文件地址,这样容易暴露地址造成盗链,这里就不说了

1、<a>标签

<a href="~/Home/download?id=1">Click to get file</a>

2、后台C#下载

html:

<a href="~/Home/download?id=1">下载</a>

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',
            );

标签:string,filePath,C#,text,image,application,小结,Response,下载
From: https://www.cnblogs.com/Dongmy/p/17673775.html

相关文章

  • C#/.NET/.NET Core优秀项目和框架8月简报
    思维导航前言FreeIMDotNetCore.SKIT.FlurlHttpClient.WechatVPetSSCMSBlog.CoreGeekDeskAgileConfigKopSoftWms加入DotNetGuide技术交流群前言公众号每月定期推广和分享的C#/.NET/.NETCore优秀项目和框架(公众号每周至少推荐两个优秀的项目和框架当然节假日除外......
  • AI绘画美女:StableDiffusion实操教程-完美世界-国漫女神云曦(附高清图下载)
    前段时间分享过StableDiffusion的入门到精通教程:AI绘画:StableDiffusion终极宝典:从入门到精通但是还有人就问:安装是安装好了,可是为什么生成的图片和你生成的图片差距那么远呢?怎么真实感和质感一个天一个地呢?其实很关键的因素,就是别人用了对的对应大模型model和专门的lora包。......
  • 如何在CMAKE中指定python路径——使用cmake为python编译扩展模块时指定python路径
     答案:cmake-DPython3_EXECUTABLE=/path/to/bin/python3   =================================================    参考:https://stackoverflow.com/questions/49908989/cmake-cant-find-python3   =================================== ......
  • docker中两个容器使用同一个IP的方法
    如果你希望允许两个容器使用相同的IP地址,可以使用Macvlan网络驱动程序。Macvlan网络驱动程序允许容器共享主机网络接口的MAC地址,从而允许多个容器使用相同的IP地址。以下是使用Macvlan网络驱动程序实现两个容器共享相同IP地址的步骤:1.创建一个Macvlan网络,指定父接口和IP地址范......
  • RTSP协议视频智能安防监控平台EasyNVR的录像播放及下载接口支持返回在线m3u8格式视频
    随着视频智能安防监控系统的普及,安防监控平台在各行各业的项目中得到了广泛应用。未来,AI智能将成为安防监控的主导方向。为了满足行业需求,TSINGSEE青犀视频不断提升现有产品的适应能力,进一步推动智能安防监控系统的发展。目前,EasyNVR作为TSINGSEE青犀视频开发的稳定可靠的智能安防......
  • c# socket tcp 通信 结构体 字节流 大端序列 小端序列
    SeerAGV_2/SeerMessage.csusingSystem.Reflection;usingSystem.Runtime.InteropServices;namespaceSeerAGV{publicstructSeerMessageHead{publicbytesync;publicbyteversion;publicushortnumber;publicuintl......
  • 排查国标GB28181视频监控平台EasyGBS无法播放且抓包返回ICMP的步骤
    GB28181视频平台EasyGBS是一个基于国标GB28181协议的视频云服务平台。它支持多路设备同时接入,并能将视频流以RTSP、RTMP、FLV、HLS、WebRTC等格式分发给多个平台和终端。该平台提供视频监控直播、云端录像、云存储、检索回放、智能告警以及语音对讲等功能。在视频能力方面,EasyGBS支......
  • 国标GB28181视频平台LiteCVR使用时出现自动删除云端录像怎么回事
    近期,我们整理并汇总了以前使用者在使用LiteCVR视频汇聚平台时遇到的技术问题反馈。为了方便大家参考,我们将逐步分享根据使用者反馈和问题描述的技术问题的解决方法及优化步骤。根据使用者的反馈,设备录像功能出现了异常。虽然设备进行了半小时的录制,但在平台上只有最近一两分钟的录......
  • EasyCVR安防视频监控平台实现环卫车的车载视频为环卫提供助力
    随着社会的不断进步和发展,文明已经成为社会精神的重要标志。为了提升城市卫生管理水平,加强基础设施项目建设,并有效控制道路扬尘,科学合理地调度和管理车辆,监督环卫作业效果、环卫车辆、环卫设施以及废弃物的处理,全程监控卫生环境,旨在及时发现并快速解决环卫作业问题。在城市文明道路......
  • LED车灯IC降压恒流驱动AP5103大功率95%高效率深度调光摩托车灯芯片
    产品描述AP5103是一款效率高,稳定可靠的LED灯恒流驱动控制芯片,内置高精度比较器,固定关断时间控制电路,恒流驱动电路等,特别适合大功率LED恒流驱动。AP5103采用ESOP8封装,散热片内置接SW脚,通过调节外置电流检测的电阻值来设置流过LED灯的电流,支持外加电压线性调光,最大电流......