C# 从服务器下载文件代码

一、//TransmitFile实现下载
    protected void Button1_Click(object sender, EventArgs e)
    {
        /*
        微软为Response对象提供了一个新的方法TransmitFile来解决使用Response.BinaryWrite
        下载超过400mb的文件时导致Aspnet_wp.exe进程回收而无法成功下载的问题。
        代码如下:
        */
        Response.ContentType = "application/x-zip-compressed";
        Response.AddHeader("Content-Disposition", "attachment;filename=z.zip");
        string filename = Server.MapPath("DownLoad/z.zip");
        Response.TransmitFile(filename);
    }

二、//WriteFile实现下载
    protected void Button2_Click(object sender, EventArgs e)
    {
        /*
        using System.IO;

        */
        string fileName = "asd.txt";//客户端保存的文件名
        string filePath = Server.MapPath("DownLoad/aaa.txt");//路径

        FileInfo fileInfo = new FileInfo(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();
    }

三、   //WriteFile分块下载
    protected void Button3_Click(object sender, EventArgs e)
    {
        string fileName = "aaa.txt";//客户端保存的文件名
        string filePath = Server.MapPath("DownLoad/aaa.txt");//路径

        System.IO.FileInfo fileInfo = new System.IO.FileInfo(filePath);

        if (fileInfo.Exists == true)
        {
            const long ChunkSize = 102400;//100K 每次读取文件,只读取100K,这样可以缓解服务器的压力
            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));
            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;
            }
            Response.Close();
        }
    }

四、//流方式下载
    protected void Button4_Click(object sender, EventArgs e)
    {
        string fileName = "aaa.txt";//客户端保存的文件名
        string filePath = Server.MapPath("DownLoad/aaa.txt");//路径

        //以字符流的形式下载文件
        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();
    }

//----------------------------------------------------------

public void DownloadFile( System.Web.UI.Page WebForm,String FileNameWhenUserDownload ,String FileBody )
{

  WebForm.Response.ClearHeaders();
  WebForm.Response.Clear();
  WebForm.Response.Expires = 0;
  WebForm.Response.Buffer = true;
  WebForm.Response.AddHeader("Accept-Language", "zh-tw");
  //‘文件名称
  WebForm.Response.AddHeader("content-disposition", "attachment; filename=‘"+System.Web.HttpUtility.UrlEncode(FileNameWhenUserDownload, System.Text.Encoding.UTF8)+"‘");
  WebForm.Response.ContentType = "Application/octet-stream";
  //‘文件内容
  WebForm.Response.Write(FileBody);//-----------
    WebForm.Response.End();
}

//上面这段代码是下载一个动态产生的文本文件,若这个文件已经存在于服务器端的实体路径,则可以通过下面的函数:

public void DownloadFileByFilePath( System.Web.UI.Page WebForm,String FileNameWhenUserDownload ,String FilePath )
{
  WebForm.Response.ClearHeaders();
  WebForm.Response.Clear();
  WebForm.Response.Expires = 0;
    WebForm.Response.Buffer = true;
  WebForm.Response.AddHeader("Accept-Language", "zh-tw");
  //文件名称
  WebForm.Response.AddHeader("content-disposition", "attachment; filename=‘" + System.Web.HttpUtility.UrlEncode(FileNameWhenUserDownload, System.Text.Encoding.UTF8) +"‘" );
  WebForm.Response.ContentType = "Application/octet-stream";
  //文件内容
  WebForm.Response.Write(System.IO.File.Rea}dAllBytes(FilePath));//---------
  WebForm.Response.End();

}
时间: 2024-08-14 02:05:08

C# 从服务器下载文件代码的相关文章

本地上传文件到服务器,从服务器下载文件到本地

最近在做项目的时候涉及到了文件的上传.下载,以前学习IO时也没有搞得多清楚,在网上找了些上传下载的例子,然后修改了部分.经测试,上传下载文件暂时能用,下面是上传和下载的方法: 1.本地上传文件到服务器 html代码: <form id="uploadDatumInfo" name="uploadDatumInfo" method="post" enctype="multipart/form-data" target=&q

Java Web实现使用浏览器从服务器下载文件(后台)

Java Web实现 使用浏览器从服务器下载文件. 下面实现两种情况的下载,需求如下: 需求(一):1.用户在页面填写表单. 2.填写完成后,选择下载,将表单内容发往后台. 3.后台根据内容生产一个文件,发送给前端. 4.前端成功下载文件到本地. 此需求简单来说就是,用户在页面上填写内容,然后将内容转变成文件的形式. 后台设计思路:1.首先拿到前端发送过来的内容. 2.将内容解析,存放至缓冲区. 3.设置响应头. 4.将缓冲区里的内容,以流的方式写出. 代码实现: public void dow

wp8通过WebClient从服务器下载文件

通过WebClient从Web服务器下载文件,并保存到wp8手机应用程序的独立存储. 我们可以通过利用webClient_DownloadStringCompleted来获得下载完成所需要的时间,用Stopwatch得到下载的总时间. 通常我们都将上传.下载作为异步事件来处理,以便不阻止主线程. String url = "http://172.18.144.248:8080/upload/" + filename; WebClient client = new WebClient()

C# 实现访问FTP服务器下载文件,获取文件夹信息小记

最近因为要开发广告制作工具,自动生成广告流,需要获取第三方服务器上的文件资源,经过摸索,从这次经历中记录下. FtpWebRequest reqFtp; WebResponse response = null; //获取文件夹信息 reqFtp = (FtpWebRequest)WebRequest.Create(this.ftp);//ftp://IP:port/文件夹名1/文件夹名2/.../文件夹名 reqFtp.UseBinary = true; reqFtp.KeepAlive = f

putty windows上传文件到linux服务器 &amp; 从linux服务器 下载文件到 windows

从putty官网下载putty软件:putty.exepscp.exepsftp.exe等软件 也可以自己下windows安装包putty-0.63-installer.exe 本人直接下载putty-0.63-installer.exe安装包了,然后直接安装 使用pscp方式从windows上传文件到linux服务器 在CMD命令行中进入到putty安装目录 输入pscp 回车 pscp 跟我们平时使用的linux scp命令操作的都是类似的 现在我直接从windows本地上传一个文件到lin

服务器下载文件http

#region 从服务器下载文件 /// <summary> /// 从服务器下载文件 /// </summary> /// <param name="_Request"></param> /// <param name="_Response"></param> /// <param name="_fileName">文件名称</param> ///

scp从服务器下载文件或上传文件到服务器

1.从服务器下载文件: scp [email protected]:/xxx/xxx.xxx e:/test/ 2.从本地上传文件到服务器 scp e:/test/test.log [email protected]:/text 理解: scp 操作的文件地址    要上传的文件地址 从服务器下载文件就好比从服务器上传文件到本地服务器 原文地址:https://www.cnblogs.com/itwlp/p/10859476.html

从Linux服务器下载文件夹到本地

从Linux服务器下载文件夹到本地1.使用scp命令 scp /home/work/source.txt [email protected]:/home/work/   #把本地的source.txt文件拷贝到192.168.0.10机器上的/home/work目录下 scp [email protected]:/home/work/source.txt /home/work/   #把192.168.0.10机器上的source.txt文件拷贝到本地的/home/work目录下 scp [em

C#实现开发windows服务实现自动从FTP服务器下载文件(自行设置分/时执行)

最近在做一个每天定点从FTP自动下载节目.xml并更新到数据库的功能.首先想到用 FileSystemWatcher来监控下载到某个目录中的文件是否发生改变,如果改变就执行相应的操作,然后用timer来设置隔多长时间来下载.后来又想想了.用windwos服务来实现吧. 效果图: 执行的Log日志: INFO-2016/5/24 0:30:07--日志内容为:0/30/7进行time触发 INFO-2016/5/24 1:30:07--日志内容为:1/30/7进行time触发 INFO-2016/