一、我需要从服务器下载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. .net转php laraval框架学习系列(三)项目实战---Route&Controllers

    本章来学习laravel的路由 一个简单的路由列子 Route::get('/', function() { return 'Hello World'; }); 路由的写法和Node的风格很相似.上面 ...

  2. Android面试题(文章内容来自他人博客)

    腾讯面试题 1.int a = 1; int result = a+++3<<2; 2.int a = 2; int result = (a++ > 2)?(++a):(a+=3); ...

  3. SharedPreferences数据、openFileOutput文件、SQLite数据库文件存储位置

    在模拟器中: SharedPreferences将XML文件保存在/data/data/<package name>/shared_prefs目录下, openFileOutput方法将文 ...

  4. 如何看懂XDEBUG+WEBGRIND?(转)

    看到一个很有用的东东,收藏.. http://blog.csdn.net/yukon12345/article/details/11408617 ~~~~~~~~~~ 使用:              ...

  5. 根据SVN的MESSAGE进行多版本输出,反向排序,真是曲折~~~啊

    import os,sys,time file = open('svnlog') revList = [] tempList = [] linen = 1 for line in file: if ( ...

  6. 开始使用Logstash

    开始使用Logstash 本节将指导处理安装Logstash 和确认一切是运行正常的, 后来的章节处理增加负载的配置来处理选择的使用案例. 这个章节包含下面的主题: Installing Logsta ...

  7. Jtree(节点的渲染+资源管理器)(2)

    上一次我们建立一个比较简单的资源管理器,这次我们说一下上面的资源管理器的问题,并且得尽量的贴近windows的资源管理器. 这样一个简单的资源管理树就完成了,下面我们说说它的问题: ① 图片和外观和W ...

  8. redis 学习笔记三(队列功能)

    Redis队列功能介绍 List 常用命令: Blpop删除,并获得该列表中的第一元素,或阻塞,直到有一个可用 Brpop删除,并获得该列表中的最后一个元素,或阻塞,直到有一个可用 Brpoplpus ...

  9. php面向对象编程之构造方法__construct()

    php中构造方法是对象创建完成后第一个被对象自动调用的方法.在每个类中都有一个构造方法,如果没有显示地声明它,那么类中都会默认存在一个没有参数且内容为空的构造方法. 构造方法的作用 通常构造方法被用来 ...

  10. <php>PDO用法二

    <?php //造PDO对象 $pdo = new PDO("mysql:dbname=mydb;host=localhost","root"," ...