一、C#实现本地文件下载

1、文件下载的路径  文件名称 以及文件下载之后要放的位置  这三个变量是必须要的

2、定义以下四个对象:

FileWebRequest ftpWebRequest = null;
FileWebResponse ftpWebResponse = null;
Stream ftpResponseStream = null;
FileStream outputStream = null;

3、创建文件下载存放位置的路径(不需要手动创建,如果路径存在就创建 不存在就不创建)

Directory.CreateDirectory(LocalFolder);//创建文件夹名称

* 这里提一点  Path.Combine()这个就是文件路径拼接的函数,会自动判断,在需要的文件加  \\

比如 string filePath=  Path.Combine(“D:”,“test”,"download");  //  filePath="D:\\test\download";

4、  然后执行以下代码  即可完成文件下载

      ftpWebRequest = (FileWebRequest)FileWebRequest.Create(new Uri(uri));
ftpWebRequest.Method = WebRequestMethods.Ftp.DownloadFile;
ftpWebResponse = (FileWebResponse)ftpWebRequest.GetResponse();
ftpResponseStream = ftpWebResponse.GetResponseStream();
long contentLength = ftpWebResponse.ContentLength;
int bufferSize = 2048;
byte[] buffer = new byte[bufferSize];
int readCount;
readCount = ftpResponseStream.Read(buffer, 0, bufferSize);
while (readCount > 0)
{
outputStream.Write(buffer, 0, readCount);
readCount = ftpResponseStream.Read(buffer, 0, bufferSize);
}

5、代码写完之后要思考,下载文件的时候如何出现异常  这时在整个代码加个 Try{} catch{}

具体代码如下:

 public static void Main(string[] args)
{
TestFile tf = new TestFile();
tf.fileDownload("D:/testFile/", "下载ftp文件.txt", "C:/Users/17/Desktop/文件", "下载ftp文件.txt", DateTime.Now.ToShortDateString());
} /// <summary>
/// 下载文件
/// </summary>
/// <param name="localPath">本地文件地址(没有文件名)</param>
/// <param name="localFileName">本地文件名</param>
/// <param name="ftpPath">下载的ftp的路径</param>
/// <param name="ftpFileName">下载的ftp的文件名</param>
public bool fileDownload(string localPath, string localFileName, string ftpPath, string ftpFileName, string date)
{
bool success = false;
//FtpWebResponse ftpWebResponse = null;
FileWebRequest ftpWebRequest = null;
FileWebResponse ftpWebResponse = null;
Stream ftpResponseStream = null;
FileStream outputStream = null;
try
{
//string date = DateTime.Now.ToShortDateString().ToString();//获取系统时间
string date1 = date.Replace("/", "");//winods 中文件命名不能有 / 去掉指定字符串 /
//localPath = localPath + date1 + "/";//拼接路径 localPath=Path.Combine(localPath,date1)
Directory.CreateDirectory(localPath);//创建文件夹名称
outputStream = new FileStream(localPath + localFileName, FileMode.Create);//创建文件
string uri = ftpRootURL + ftpPath + "/" + ftpFileName;//拼接目标文件路径 string uri= Path.Combine(ftpRootURL,ftpPath,ftpFileName);
ftpWebRequest = (FileWebRequest)FileWebRequest.Create(new Uri(uri));
//ftpWebRequest1.UseBinary = true;
ftpWebRequest.Method = WebRequestMethods.Ftp.DownloadFile;
ftpWebResponse = (FileWebResponse)ftpWebRequest.GetResponse();
ftpResponseStream = ftpWebResponse.GetResponseStream();
long contentLength = ftpWebResponse.ContentLength;
int bufferSize = 2048;
byte[] buffer = new byte[bufferSize];
int readCount;
readCount = ftpResponseStream.Read(buffer, 0, bufferSize);
while (readCount > 0)
{
outputStream.Write(buffer, 0, readCount);
readCount = ftpResponseStream.Read(buffer, 0, bufferSize);
}
success = true;
}
catch (Exception e)
{ DirectoryInfo folder = new DirectoryInfo(localPath);
StreamWriter log = new StreamWriter(localPath + "/" + DateTime.Now.ToShortDateString().ToString().Replace("/", "") + ".txt", true);
log.WriteLine("发生异常时间:" + System.DateTime.Now.ToShortTimeString().ToString());
log.WriteLine("发生异常信息:" + e.Message);
log.WriteLine("发送异常对象:" + e.Source);
log.WriteLine("调用堆栈:" + e.StackTrace.Trim());
log.WriteLine("触动方法:" + e.TargetSite);
log.WriteLine(" " + e.HResult);
log.WriteLine("数据对象" + e.Data);
log.WriteLine("____________________________________________________________");
log.WriteLine();
log.Close();
success = false;
}
finally
{
if (outputStream != null)
{
outputStream.Close();
}
if (ftpResponseStream != null)
{
ftpResponseStream.Close();
} if (ftpWebResponse != null)
{
ftpWebResponse.Close();
}
}
return success;
}

二、 FTP 服务文件下载

这个功能其实和本地文件下载一样,只需要加几点即可

1、FTP服务的地址;

具体代码如下

private string ftpIP = "**********";

2、FTP文件服务的登录账号以及密码

具体代码如下

private string ftpName = "*********";
private string ftpPassword = "******";
private string ftpRootURL = string.Empty;
FtpWebRequest reqFTP;

3、获取FTP服务上的文件名称、FTP文件服务需要下载之后存放的路径以及下载功能的实现

FtpWebRequest ftpWebRequest = null;
FtpWebResponse ftpWebResponse = null;
Stream ftpResponseStream = null;
FileStream outputStream = null;
try
{
localFilePath = Path.Combine(localFilePath, ftpFileNameTime);
Directory.CreateDirectory(localFilePath);//创建文件夹名称
outputStream = new FileStream(Path.Combine(localFilePath, fileName), FileMode.Create);
string uri = Path.Combine(ftpRootURL, ftpIP, fileName);
ftpWebRequest = (FtpWebRequest)FileWebRequest.Create(new Uri(uri));
ftpWebRequest.Credentials = new NetworkCredential(ftpName, ftpPassword);//登录ftp
ftpWebRequest.UseBinary = true;
ftpWebRequest.Method = WebRequestMethods.Ftp.DownloadFile;
ftpWebResponse = (FtpWebResponse)ftpWebRequest.GetResponse();
ftpResponseStream = ftpWebResponse.GetResponseStream();
long contentLength = ftpWebResponse.ContentLength;
int bufferSize = 2048;
byte[] buffer = new byte[bufferSize];
int readCount;
readCount = ftpResponseStream.Read(buffer, 0, bufferSize);
while (readCount > 0)
{
outputStream.Write(buffer, 0, readCount);
readCount = ftpResponseStream.Read(buffer, 0, bufferSize);
}
}
catch (Exception ex)
{ MessageBox.Show(ex.Message)
/*MessageBox.Show(ex.Message + "是否下载日志文件", "发送错误!", MessageBoxButtons.OKCancel);
//点击确定 就执行下载日志文件,不然就不执行
if (dr == DialogResult.OK)
{
WriteLog log = new WriteLog();
log.Write_log(ex.Message);
}*/
}
finally
{
if (outputStream != null)
{
outputStream.Close();
}
if (ftpResponseStream != null)
{
ftpResponseStream.Close();
} if (ftpWebResponse != null)
{
ftpWebResponse.Close();
}
}

5、具体代码如下:

namespace FtpDownLoad
{
public class ftpFileDownload
{ private string ftpIP = "*************";
private string ftpName = "2*******";
private string ftpPassword = "*********";
private string ftpRootURL = string.Empty;
FtpWebRequest reqFTP; public static void Main(string[] args)
{ ftpFileDownload ftpDown = new ftpFileDownload();
ftpDown.GetFileList("D:\testFile","37.pdt","20190703"); } /// <summary>
/// 文件下载
/// </summary>
/// <param name="localFilePath">下载路径</param>
/// <param name="fileName">下载的名称</param>
/// <param name="ftpFilePath">FTP路径</param>
/// <param name="ftpFileNameTime">FTP文件的修改时间</param> public void FtpDownLoadFile(string localFilePath, string fileName, string ftpFileNameTime)
{
FtpWebRequest ftpWebRequest = null;
FtpWebResponse ftpWebResponse = null;
Stream ftpResponseStream = null;
FileStream outputStream = null;
try
{
localFilePath = Path.Combine(localFilePath, ftpFileNameTime);
Directory.CreateDirectory(localFilePath);//创建文件夹名称
outputStream = new FileStream(Path.Combine(localFilePath, fileName), FileMode.Create);
string uri = Path.Combine(ftpRootURL, ftpIP, fileName);
ftpWebRequest = (FtpWebRequest)FileWebRequest.Create(new Uri(uri));
ftpWebRequest.Credentials = new NetworkCredential(ftpName, ftpPassword);//登录ftp
ftpWebRequest.UseBinary = true;
ftpWebRequest.Method = WebRequestMethods.Ftp.DownloadFile;
ftpWebResponse = (FtpWebResponse)ftpWebRequest.GetResponse();
ftpResponseStream = ftpWebResponse.GetResponseStream();
long contentLength = ftpWebResponse.ContentLength;
int bufferSize = 2048;
byte[] buffer = new byte[bufferSize];
int readCount;
readCount = ftpResponseStream.Read(buffer, 0, bufferSize);
while (readCount > 0)
{
outputStream.Write(buffer, 0, readCount);
readCount = ftpResponseStream.Read(buffer, 0, bufferSize);
}
}
catch (Exception ex)
{ MessageBox.Show(ex.Message);
/* DialogResult dr = MessageBox.Show(ex.Message + "是否下载日志文件", "发送错误!", MessageBoxButtons.OKCancel);
//点击确定 就执行下载日志文件,不然就不执行
if (dr == DialogResult.OK)
{
WriteLog log = new WriteLog();
log.Write_log(ex.Message);
}*/
}
finally
{
if (outputStream != null)
{
outputStream.Close();
}
if (ftpResponseStream != null)
{
ftpResponseStream.Close();
} if (ftpWebResponse != null)
{
ftpWebResponse.Close();
}
}
}

如有疑问  可以往773408602@qq.com发邮件,我会第一时间给你解答的

C#本地文件下载以及FTP文件服务下载(以Pdf文件为例)的更多相关文章

  1. 用DOS批处理实现FTP自动上传、下载、清理文件

    用DOS批处理实现FTP自动上传.下载.清理文件 最近好像特别的忙,好久没来写点东西了,今天写了一个利用批处理程序完成FTP自动上传.下载.清理文件的程序.赶紧 记录下来,以备日后之用.功能介绍:自动 ...

  2. IOS下载查看PDF文件(有下载进度)

    IOS(object-c) 下载查看 PDF 其实还是蛮容易操作的.在下载前,首先要把 IOS 可以保存文件的目录给过一遍: IOS 文件保存目录 IOS 可以自定义写入的文件目录,是很有限的,只能是 ...

  3. word和.txt文件转html 及pdf文件, 使用poi jsoup itext心得

    word和.txt文件转html 及pdf文件, 使用poi jsoup  itext心得本人第一次写博客,有上面不足的或者需要改正的希望大家指出来,一起学习交流讨论.由于在项目中遇到了这一个问题,在 ...

  4. PDF文件怎么修改,PDF文件编辑方法

    PDF文件是一种独特的文件,在日常办公中已经成为我们使用最广泛的电子文档格式.在使用PDF文件中会遇到PDF文件有错区的时候,再从新制作一个PDF文件会比较麻烦,只能通过工具来对PDF文件进行修改,这 ...

  5. 轻松将CAD文件转为加密的PDF文件

    对于从事设计相关工作的朋友来说,CAD肯定再熟悉不过了.一些有特殊要求的CAD文件,需要将其转换成为PDF文件以方便保存.传输.打印,同时还得保证设计图稿的安全性,所以将CAD文件直接转为加密的PDF ...

  6. C#将制定文件夹下的PDF文件合并成一个并输出至指定路径

    /// <summary> /// 将源路径下的PDF合并至目标路径下 /// </summary> /// <param name="SourcePath&q ...

  7. 【文件】java生成PDF文件

    package test; import java.awt.Color; import java.io.FileOutputStream; import org.junit.Test; import ...

  8. 递归找到多级文件夹中所有pdf文件的py程序

    因个人需要,写了一个可以递归找到多级文件夹中所有pdf的小程序,发布出来供有需要的人参考或使用. import os import re import shutil from os.path impo ...

  9. 从 FTP 服务器上下载并保存文件

    本例演示如何运用 C# 中的 FtpWebRequest 等对象从 FTP 服务器上获取文件,并结合 Stream 对象中的方法来保存下载的文件: using System; using System ...

随机推荐

  1. Python批量检测服务器端口可用性与Socket函数使用

    socket函数 简述 socket又称套间字或者插口,是网络通信中必不可少的工具.有道是:"无socket,不网络".由于socket最早在BSD Unix上使用,而Unix/L ...

  2. Kubernetes增强型调度器Volcano算法分析

    [摘要] Volcano 是基于 Kubernetes 的批处理系统,源自于华为云开源出来的.Volcano 方便 AI.大数据.基因.渲染等诸多行业通用计算框架接入,提供高性能任务调度引擎,高性能异 ...

  3. Python高级学习笔记

    Python高级学习笔记,此笔记中包含Linux操作系统.Html+CSS+JS.网络协议等. 所有思维导图为本人亲手所画,请勿用于商用. 大哥们,求点赞哦. 第一天笔记:链接 第二天笔记:链接 第三 ...

  4. 转:spring4.0之二:@Configuration的使用

    从Spring3.0,@Configuration用于定义配置类,可替换xml配置文件,被注解的类内部包含有一个或多个被@Bean注解的方法,这些方法将会被AnnotationConfigApplic ...

  5. Spring bean 初始化失败

    在一个*context.xml 配置文件 A 中, 有个定义的bean B, 把 A 添加到 application-context.xml 中,发现B不能正常初始化. 解决办法: 添加 <co ...

  6. golang包管理的古往今来

    https://golang.org/ before GO1.5-GOPATH 在GO1.5之前用GOPATH以及GOROOT这两个环境变量来决定包的位置. GOROOT就是告知当前go的安装位置,编 ...

  7. Orleans 初接触

    简介 这篇随笔主要记录了自己学习Orleans的经过和理解,在学习过程中会一直更新,思路和理解可能有些偏颇,如果有幸有大佬看到这篇文章,希望能给予批评指正. 导航 (一) 入门例子 (二) 测试用例 ...

  8. web漏洞-命令执行、文件上传、XSS

    一.命令执行   1:什么是命令执行? 命令执行漏洞是指攻击者可以随意执行系统命令.属于高危漏洞之一任何脚本语言都可以调用操作系统命令. 应用有时需要调用一些执行系统命令的函数,举个例子如:PHP中的 ...

  9. 重新精读《Java 编程思想》系列之向上转型与向下转型

    前言 今天重读了一下向上转型与向下转型,有些新的体会,了解了向上转型的好处,及如何向下转型.在此分享给大家. 向上转型 向上转型是用来表现新类和基类之间的关系.在传统中,由导出类转型成基类,在继承图中 ...

  10. C语言中表达n次方

    C语言中表达n次方可以用pow函数. 函数原型:double pow(double x, double y) 功    能:计算x^y的值 返 回 值:计算结果 举例: double a; a = p ...