一、我需要从服务器下载ppt文件到本地

protected void Btn_DownPPT_Click(object sender, EventArgs e)
        {
            DBService svc = new DBService();
            svc.DownPpts();
            string strFileName = "公报.ppt";
            string filename = Context.Server.MapPath(Context.Request.ApplicationPath) + "\\Temp\\" + strFileName; //物理地址

if (strFileName != "")
            {
                string path = Context.Server.MapPath(Context.Request.ApplicationPath) + "\\Temp\\" + strFileName;//物理地址
                System.IO.FileInfo file = new System.IO.FileInfo(path);
                if (file.Exists)
                {
                    Response.Clear();
                    Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name); //中文文件名会乱码

Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(file.Name, System.Text.Encoding.UTF8));
                    Response.AddHeader("Content-Length", file.Length.ToString());
                    Response.ContentType = "application/octet-stream";
                    Response.Filter.Close();
                    Response.WriteFile(file.FullName);
                    Response.End();
                }
                else
                {
                    Response.Write("This file does not exist.");
                }
            }
        }

以下转载:http://www.alixixi.com/Dev/Web/ASPNET/aspnet1/2007/2007050633864.html

string filename = "a.txt";

if (filename != "")
        {

string path = Server.MapPath(filename);

System.IO.FileInfo file = new System.IO.FileInfo(path);

if (file.Exists)
            {

Response.Clear();

Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);

Response.AddHeader("Content-Length", file.Length.ToString());

Response.ContentType = "application/octet-stream";

Response.Filter.Close();

Response.WriteFile(file.FullName);

Response.End();

}

else
            {

Response.Write("This file does not exist.");

}

}

转载自:http://blog.csdn.net/zlhzhj/article/details/7563762

  • 局域网文件下载:

public class RemoteDownload
    {
        public static void DownLoad(string addressUrl,string localName)
        {
            //下载文件
            System.Net.WebClient myWebClient = new System.Net.WebClient();
            myWebClient.DownloadFile(@"/10.2.0.254/software/01279.lic.txt", "testdownload.txt");           
            //下载end
        }
    }

通过URL获取页面内容

try
            {
                // 远程获取目标页面源码
                string strTargetHtml = string.Empty;
                WebClient wc = new WebClient();
                wc.Credentials = CredentialCache.DefaultCredentials;
                byte[] btPageData = wc.DownloadData(strTargetUrl + dtTargetDate.ToString("yyyy") + "/" + dtTargetDate.ToString("MM") + "/" + dtTargetDate.ToString("dd") + "/");
                strTargetHtml = Encoding.UTF8.GetString(btPageData);
                wc.Dispose();
            }
            catch(Exception exp)
            {
                _isError = true;
                _errorDetail = "获取目标日志文件列表时出错:" + exp.Message;
            }

  • 通过web方式,从远程服务器端下载文件:

public class WebDownload
    {
        public static void DownLoad(string Url, string FileName)
        {
            bool Value = false;
            WebResponse response = null;
            Stream stream = null;

try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);

response = request.GetResponse();
                stream = response.GetResponseStream();

if (!response.ContentType.ToLower().StartsWith("text/"))
                {
                    Value = SaveBinaryFile(response, FileName);

}

}
            catch (Exception err)
            {
                string aa = err.ToString();
            }

}

/// <summary>
        /// Save a binary file to disk.
        /// </summary>
        /// <param name="response">The response used to save the file</param>
        // 将二进制文件保存到磁盘
        private static bool SaveBinaryFile(WebResponse response, string FileName)
        {
            bool Value = true;
            byte[] buffer = new byte[1024];

try
            {
                if (File.Exists(FileName))
                    File.Delete(FileName);
                Stream outStream = System.IO.File.Create(FileName);
                Stream inStream = response.GetResponseStream();

int l;
                do
                {
                    l = inStream.Read(buffer, 0, buffer.Length);
                    if (l > 0)
                        outStream.Write(buffer, 0, l);
                }
                while (l > 0);

outStream.Close();
                inStream.Close();
            }
            catch
            {
                Value = false;
            }
            return Value;
        }

  • 从FTP上下载文件:

public class FtpDownload
    {
        public static void DownLoad(string FtpPath)
        {
            /*首先从配置文件读取ftp的登录信息*/
            string TempFolderPath = System.Configuration.ConfigurationManager.AppSettings["TempFolderPath"].ToString();
            string FtpUserName = System.Configuration.ConfigurationManager.AppSettings["FtpUserName"].ToString();
            string FtpPassWord = System.Configuration.ConfigurationManager.AppSettings["FtpPassWord"].ToString();
            string LocalFileExistsOperation = System.Configuration.ConfigurationManager.AppSettings["LocalFileExistsOperation"].ToString();

Uri uri = new Uri(FtpPath);
            string FileName = Path.GetFullPath(TempFolderPath) + Path.DirectorySeparatorChar.ToString() + Path.GetFileName(uri.LocalPath);

//创建一个文件流
            FileStream fs = null;
            Stream responseStream = null;
            try
            {
                //创建一个与FTP服务器联系的FtpWebRequest对象
                FtpWebRequest request = (FtpWebRequest)WebRequest.Create(uri);
                //设置请求的方法是FTP文件下载
                request.Method = WebRequestMethods.Ftp.DownloadFile;

//连接登录FTP服务器
                request.Credentials = new NetworkCredential(FtpUserName, FtpPassWord);

//获取一个请求响应对象
                FtpWebResponse response = (FtpWebResponse)request.GetResponse();
                //获取请求的响应流
                responseStream = response.GetResponseStream();

//判断本地文件是否存在,如果存在,则打开和重写本地文件

if (File.Exists(FileName))
                {
                    if (LocalFileExistsOperation == "write")
                    {
                        fs = File.Open(FileName, FileMode.Open, FileAccess.ReadWrite);

}
                }

//判断本地文件是否存在,如果不存在,则创建本地文件
                else
                {
                    fs = File.Create(FileName);
                }

if (fs != null)
                {

int buffer_count = 65536;
                    byte[] buffer = new byte[buffer_count];
                    int size = 0;
                    while ((size = responseStream.Read(buffer, 0, buffer_count)) > 0)
                    {
                        fs.Write(buffer, 0, size);

}
                    fs.Flush();
                    fs.Close();
                    responseStream.Close();
                }
            }
            finally
            {
                if (fs != null)
                    fs.Close();
                if (responseStream != null)
                    responseStream.Close();
            }

}
    }

asp.net从服务器(指定文件夹)下载任意格式的文件到本地的更多相关文章

  1. C#实现FTP文件夹下载功能【转载】

    网上有很多FTP单个文件下载的方法,前段时间需要用到一个FTP文件夹下载的功能,于是找了下网上的相关资料结合MSDN实现了一段FTP文件夹下载的代码. 实现的思路主要是通过遍历获得文件夹下的所有文件, ...

  2. Python——合并指定文件夹下的所有excel文件

    前提:该文件夹下所有文件有表头且具有相同的表头. import glob # 同下 from numpy import * #请提前在CMD下安装完毕,pip install numppy impor ...

  3. C#_IO操作_查询指定文件夹下的每个子文件夹占空间的大小

    1.前言 磁盘内存用掉太多,想查那些文件夹占的内存比较大,再找出没有用的文件去删除. 2.代码 static void Main(string[] args) { while (true) { //指 ...

  4. jq+download+文件夹下载

    最近公司在做工程项目,实现文件夹下载. 网上找了很久,发现网上的代码都有相似的问题,不过最终还是让我找到了一个符合的项目. 工程: 进行项目文件夹下载功能分析,弄清楚文件夹下载的原理,提供的数据支持. ...

  5. Github文件夹下载到本地

    1.如图:需要将以下文件夹下载到本地. https://github.com/aspnet/Docs/tree/master/aspnet/mvc/overview/getting-started/i ...

  6. Python小代码_15_遍历指定路径下的所有文件和文件夹,并格式化输出文件路径文件名和文件夹名,文件大小,修改时间

    遍历指定路径下的所有文件和文件夹,并格式化输出文件路径文件名和文件夹名,文件大小,修改时间 import osimport datetime def print_tree(dir_path): for ...

  7. Java以流的方式将指定文件夹里的.txt文件全部复制到另一文件夹,并删除原文件夹中所有.txt文件

    import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.Fi ...

  8. MATLAB读取一个文件夹下的多个子文件夹中的多个指定格式的文件

    MATLAB需要读取一个文件夹下的多个子文件夹中的指定格式文件,这里以读取*.JPG格式的文件为例 1.首先确定包含多个子文件夹的总文件夹 maindir = 'C:\Temp Folder'; 2. ...

  9. 【JAVA】编程(6)--- 应用IO流拷贝文件夹(内含多个文件)到指定位置

    此程序应用了: File 类,及其常用方法: FileInputStream,FileOutputStream类及其常用方法: 递归思维: package com.bjpowernode.javase ...

随机推荐

  1. 常见Oracle数据库问题总结及解决办法(一)

    开发中常使用Oralce数据库,使用中也许会碰到形形色色的各类错误提示,如:ORA-00933:SQL命令未正确结束.ORA-009242等等,为此记录积累对于自己来说还是很有帮助的,今天就记录以前出 ...

  2. 服务器端操作Cookie[2]

    服务器端操作Cookie,主要注意会使用以下三个类: HttpCookie,HttpResponse,HttpRequest 关于HttpCookie: 属性 描述 例子 Domain 获取或设置与此 ...

  3. effective_c++条款20,用pass-by-reference-to-const替换pass-by-value

    pass-by-value void f(A a); 1)导致复制是浪费资源 2)多态是导致对象切割 所以我们使用 void f(const A& a) 上面的话针对class,不针对基本类型 ...

  4. bestcoder r44 p3 hdu 5270 ZYB loves Xor II

    这是昨晚队友跟我说的题,不知道当时是什么玄幻的事件发生了,,我看成了两两相乘的XOR 纠结了好长时间间 不知道该怎么办 今天早上看了下这道题,发现是两两相加的XOR  然后就想了想昨晚的思路 发现可做 ...

  5. Redis VS Memcached 转载

    引子: 在大数据时代,总希望存在一个Key-value存储机制,像HashMap一样在内存中处理大量(千万数量级)的key-value对,以便提高数据查找.修改速度. 所以,我们会想到,Memcach ...

  6. linux 下使用crontab+wget实现秒及定时任务

    输入命令 crontab -e 打开一个文件,默认的编辑器为vi. 输入vi编辑器,输入i为插入,输入w保存,q退出,!强制.wq!强制保存并退出. * * * * * /usr/bin/wget - ...

  7. 浅析JavaScript和PHP中三个等号(===)和两个等号(==)的区别

    先做个简单的介绍,让先有个直观的认识 == equality 等同 === identity 恒等 == 两边值类型不同的时候,要先进行类型转换,再比较. === 不做类型转换,类型不同的一定不等. ...

  8. Python -- 大小写转换

    #小写转大写 strs = 'abcd' strs = strs.upper() print u'abcd小写转大写:', strs #大写转小写 strs = 'ABCD' strs = strs. ...

  9. 未能在全局命名空间中找到类型或命名空间名称“Wuqi”

    下载了AspNetPager控件用以进行分页操作,在项目中放入控件后,运行报错:未能在全局命名空间中找到类型或命名空间名称“Wuqi” . 解决办法:在项目下拉框“引用“中添加AspNetPager引 ...

  10. JavaWeb学习笔记--4.EL表达式

    四. 表达式语言(相当于对JSP中对象输出的简化,功能实质上类似) 转自ZHSJUN的博客 http://blog.csdn.net/zhsjun/article/details/2254546 表达 ...