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

一、我需要从服务器下载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-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从服务器(指定文件夹)下载任意格式的文件到本地

时间: 2024-08-25 16:50:52

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

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

网上有很多FTP单个文件下载的方法,前段时间需要用到一个FTP文件夹下载的功能,于是找了下网上的相关资料结合MSDN实现了一段FTP文件夹下载的代码. 实现的思路主要是通过遍历获得文件夹下的所有文件,当然,文件夹下可能仍然存在文件夹,这样就需要结合递归这种方法来实现对一个我们指定的文件夹获得其下的所有文件.最后通过一个下载方法来逐级将文件夹内的每个文件下载到本地. 有关递归的MSDN在线帮助--http://msdn.microsoft.com/zh-cn/library/z3dk2cc3.as

删除指定文件夹中除保留的文件外的所有文件批处理 删除指定文件夹下的空文件夹,包括子目录批处理

删除指定文件夹中除保留的文件外的所有文件批处理 @echo off set "ext= sln csproj" for /f "delims=" %%a in ('dir /b/s/a-d *.*') do ( set .= if /i not "%%~nxa"=="%~nx0" ( for %%i in (%ext%) do if /i "%%~xa"==".%%i" set .=.

android XMl 解析神奇xstream 一: 解析android项目中 asset 文件夹 下的 aa.xml 文件

1.下载工具 xstream 下载最新版本地址: https://nexus.codehaus.org/content/repositories/releases/com/thoughtworks/xstream/ 下载完成后 把jar包导入到自己的android项目中 2.asset 文件夹 下的 aa.xml 文件 <?xml version="1.0" encoding="UTF-8"?><product>    <name>

【转】C#打包文件夹成zip格式

原文地址 C#打包文件夹成zip格式(包括文件夹和子文件夹下的所有文件)C#打包zip文件可以调用现成的第三方dll,事半功倍,而且该dll完全免费,下载地址:SharpZipLib下载完解压缩后,把 ICSharpCode.SharpZipLib.dll 拷贝到当前项目的目录下(如果偷懒的话,可以直接拷贝到当前项目的bin\Debug目录下),在VS打开的项目引用上右键添加引用 ICSharpCode.SharpZipLib.dll然后,在VS打开的项目上右键新建一个类,命名为 ZipHelp

Ant步步为营(5)用for和foreach的方法遍历一个文件夹,查找到某个文件并删除

今天有个任务是要删除VM上的某个文件夹下的两个jar包.不过这个任务没有分配给我,而是分配给俺的师傅,哈哈.不过我还是自己动手写了一些脚本在本地模拟一下删除某个指定文件. build.xml <?xml version="1.0"?>    <project name="ForTest" default="build" >    <property file="build.properties"&

Web 在线文件管理器学习笔记与总结(15)剪切文件夹 (16)删除文件夹

(15)剪切文件夹 ① 通过rename($oldname,$newname) 函数实现剪切文件夹的操作 ② 需要检测目标文件夹是否存在,如果存在还要检测目标目录中是否存在同名文件夹,如果不存在则剪切 dir.function.php 添加: //剪切文件夹 function cutFolder($src,$dst){ if(!file_exists($dst)){ return '目标目录不存在'; }else{ if(!is_dir($dst)){ return '不是目录'; }else{

python判断文件和文件夹是否存在、创建文件夹

>>> import os >>> os.path.exists('d:/assist') True >>> os.path.exists('d:/assist/getTeacherList.py') True >>> os.path.isfile('d:/assist') False >>> os.path.isfile('d:/assist/getTeacherList.py') True >>>

执行某个文件夹下面的所有.py文件

# 写一个函数,接受一个参数,如果是文件,就执行这个文件,如果是文件夹,就执行这个文件夹下所有的py文件 # 工作应用场景,假设一个文件夹下面有100个py文件,同步一些时间 # 例如抢票软件 10点钟放票, 所有的机器要同步时间,同步代码,每台机器卖了多少票要定时回传给服务器回传信息 # 假设所做的事情都放在py文件里,放十几二十个,这时候就可以写一个程序,每过一个小时就执行一次所有的py文件 import os # 执行一个文件里所有的文件,比如 def func(path): # 先判断这

使用ftp读取文件夹中的多个文件,并删除

public class FTPUtils { private static final Logger LOG = LoggerFactory.getLogger(FTPUtils.class); /** * 获取FTPClient对象 * * @param ftpHost FTP主机服务器 * @param ftpPassword FTP 登录密码 * @param ftpUserName FTP登录用户名 * @param ftpPort FTP端口 默认为21 * @return */ p