public class FtpService
{
#region Fields and attributes
private readonly int BufLen = 2048;
/// <summary>
/// ftp服务器地址
/// </summary>
private readonly string FtpServer = Properties.Settings.Default.FtpServer;
/// <summary>
/// ftp用户名
/// </summary>
private readonly string FtpUser = Properties.Settings.Default.user;
/// <summary>
/// ftp密码
/// </summary>
private readonly string FtpPassword = Properties.Settings.Default.password;
#endregion #region Events
/// <summary>
/// 文件上传结果
/// </summary>
/// <param>true-成功,false-失败</param>
/// <param>信息</param>
public event Action<bool, string> EventUploadResult = null;
/// <summary>
/// 文件上传进度
/// </summary>
/// <param>文件已上传大小</param>
/// <param>文件总大小</param>
/// <param>文件名称</param>
public event Action<long, long, string> EventUploadFileProgress = null;
/// <summary>
/// 所有文件上传进度
/// </summary>
/// <param>文件已上传数</param>
/// <param>文件总总数</param>
public event Action<int, int> EventUploadBatchFilesProgress = null;
/// <summary>
/// 文件下载结果
/// </summary>
/// <param>true-成功,false-失败</param>
/// <param>信息</param>
public event Action<bool, string> EventDonwloadResult = null;
/// <summary>
/// 文件下载进度
/// </summary>
/// <param>文件已下载大小</param>
/// <param>文件总大小</param>
/// <param>文件名称</param>
public event Action<long, long, string> EventDonwloadFileProgress = null;
/// <summary>
/// 所有文件下载进度
/// </summary>
/// <param>文件已下载数</param>
/// <param>文件总总数</param>
public event Action<int, int> EventDonwloadBatchFilesProgress = null;
#endregion #region public methods
/// <summary>
/// 上传文件到FTPServer
/// </summary>
/// <param name="file"></param>
public bool UploadFile(string localFilePath)
{
if (string.IsNullOrEmpty(localFilePath))
return false; bool ret = true;
FtpWebRequest reqFtp = null;
try
{
FileInfo localFileInfo = new FileInfo(localFilePath);
string serverFilePath = $@"{FtpServer}\{ localFileInfo.Name}"; //FtpWebRequest配置
reqFtp = (FtpWebRequest)FtpWebRequest.Create(new Uri(serverFilePath));
reqFtp.UseBinary = true;
reqFtp.Credentials = new NetworkCredential(FtpUser, FtpPassword); //设置通信凭据
reqFtp.KeepAlive = false;
reqFtp.Method = WebRequestMethods.Ftp.UploadFile;
reqFtp.ContentLength = localFileInfo.Length; //读本地文件数据并上传
using (FileStream fileStream = localFileInfo.OpenRead())
{
using (Stream stream = reqFtp.GetRequestStream())
{
long totalLen = 0;
int contentLen = 0;
byte[] buff = new byte[BufLen];
while ((contentLen = fileStream.Read(buff, 0, BufLen)) > 0)
{
stream.Write(buff, 0, contentLen);
totalLen += contentLen;
if (EventUploadFileProgress != null)
EventUploadFileProgress(totalLen, localFileInfo.Length, localFileInfo.Name);
}
}
} ret = true;
if (EventUploadResult != null)
EventUploadResult(ret, $@"{localFilePath} : 上传成功!");
}
catch (Exception ex)
{
ret = false;
if (EventUploadResult != null)
EventUploadResult(ret, $@"{localFilePath} : 上传失败!Exception : {ex.ToString()}");
}
finally
{
if (reqFtp != null)
reqFtp.Abort();
} return ret;
} /// <summary>
/// 从FTPServer上下载文件
/// </summary>
public bool DownloadFile(string fileName, long length, string localDirectory)
{
if (string.IsNullOrEmpty(localDirectory) || string.IsNullOrEmpty(fileName))
return false; bool ret = true;
FtpWebRequest reqFtp = null;
FtpWebResponse respFtp = null;
string localFilePath = $@"{localDirectory}\{fileName}";
string serverFilePath = $@"{FtpServer}\{fileName}"; try
{
if (File.Exists(localFilePath))
File.Delete(localFilePath); //建立ftp连接
reqFtp = (FtpWebRequest)FtpWebRequest.Create(new Uri(serverFilePath));
reqFtp.UseBinary = true;
reqFtp.Credentials = new NetworkCredential(FtpUser, FtpPassword);
reqFtp.KeepAlive = false;
reqFtp.Method = WebRequestMethods.Ftp.DownloadFile; //读服务器文件数据并写入本地文件
respFtp = reqFtp.GetResponse() as FtpWebResponse;
using (Stream stream = respFtp.GetResponseStream())
{
using (FileStream fileStream = new FileStream(localFilePath, FileMode.Create))
{
long totalLen = 0;
int contentLen = 0;
byte[] buff = new byte[BufLen];
while ((contentLen = stream.Read(buff, 0, BufLen)) > 0)
{
fileStream.Write(buff, 0, contentLen);
totalLen += contentLen;
if (EventDonwloadFileProgress != null && length > 0)
EventDonwloadFileProgress(totalLen, length, fileName);
}
}
} ret = true;
if (EventDonwloadResult != null)
EventDonwloadResult(ret, $@"{serverFilePath} : 下载成功!");
}
catch (Exception ex)
{
ret = false;
if (EventDonwloadResult != null)
EventDonwloadResult(ret, $@"{serverFilePath} : 下载失败!Exception : {ex.ToString()}");
}
finally
{
if (reqFtp != null)
reqFtp.Abort();
if (respFtp != null)
respFtp.Close();
} return ret;
} /// <summary>
/// 批量上传文件
/// </summary>
/// <param name="localFilePaths"></param>
public void UploadFiles(List<string> localFilePaths)
{
if (localFilePaths == null || localFilePaths.Count == 0)
return; int i = 1;
foreach (var localFilePath in localFilePaths)
{
UploadFile(localFilePath);
if (EventUploadBatchFilesProgress != null)
EventUploadBatchFilesProgress(i++, localFilePaths.Count);
}
} /// <summary>
/// 批量下载文件
/// </summary>
/// <param name="fileNames"></param>
/// <param name="localDirectory"></param>
public void DownloadFiles(List<FileModel> files, string localDirectory)
{
if (files == null || files.Count == 0 || string.IsNullOrEmpty(localDirectory))
return; int i = 1;
foreach (var file in files)
{
DownloadFile(file.Name, file.Size, localDirectory);
if (EventDonwloadBatchFilesProgress != null)
EventDonwloadBatchFilesProgress(i++, files.Count);
}
} /// <summary>
/// 异步上传文件到FTPServer
/// </summary>
/// <param name="file"></param>
public async Task<bool> UploadFileAsync(string localFilePath)
{
if (string.IsNullOrEmpty(localFilePath))
return false; bool ret = true;
FtpWebRequest reqFtp = null;
try
{
FileInfo localFileInfo = new FileInfo(localFilePath);
string serverFilePath = $@"{FtpServer}\{ localFileInfo.Name}"; //FtpWebRequest配置
reqFtp = (FtpWebRequest)FtpWebRequest.Create(new Uri(serverFilePath));
reqFtp.UseBinary = true;
reqFtp.Credentials = new NetworkCredential(FtpUser, FtpPassword); //设置通信凭据
reqFtp.KeepAlive = false;
reqFtp.Method = WebRequestMethods.Ftp.UploadFile;
reqFtp.ContentLength = localFileInfo.Length; //读本地文件数据并上传
using (FileStream fileStream = localFileInfo.OpenRead())
{
using (Stream stream = await reqFtp.GetRequestStreamAsync())
{
long totalLen = 0;
int contentLen = 0;
byte[] buff = new byte[BufLen];
while ((contentLen = await fileStream.ReadAsync(buff, 0, BufLen)) > 0)
{
await stream.WriteAsync(buff, 0, contentLen);
totalLen += contentLen;
if (EventUploadFileProgress != null)
EventUploadFileProgress(totalLen, localFileInfo.Length, localFileInfo.Name);
}
}
} ret = true;
if (EventUploadResult != null)
EventUploadResult(ret, $@"{localFilePath} : 上传成功!");
}
catch (Exception ex)
{
ret = false;
if (EventUploadResult != null)
EventUploadResult(ret, $@"{localFilePath} : 上传失败!Exception : {ex.ToString()}");
}
finally
{
if (reqFtp != null)
reqFtp.Abort();
} return ret;
} /// <summary>
/// 异步从FTPServer上下载文件
/// </summary>
public async Task<bool> DownloadFileAsync(string fileName, long length, string localDirectory)
{
if (string.IsNullOrEmpty(localDirectory) || string.IsNullOrEmpty(fileName))
return false; bool ret = true;
FtpWebRequest reqFtp = null;
FtpWebResponse respFtp = null;
string localFilePath = $@"{localDirectory}\{fileName}";
string serverFilePath = $@"{FtpServer}\{fileName}"; try
{
if (File.Exists(localFilePath))
File.Delete(localFilePath); //建立ftp连接
reqFtp = (FtpWebRequest)FtpWebRequest.Create(new Uri(serverFilePath));
reqFtp.UseBinary = true;
reqFtp.Credentials = new NetworkCredential(FtpUser, FtpPassword);
reqFtp.KeepAlive = false;
reqFtp.Method = WebRequestMethods.Ftp.DownloadFile; //读服务器文件数据并写入本地文件
respFtp = await reqFtp.GetResponseAsync() as FtpWebResponse;
using (Stream stream = respFtp.GetResponseStream())
{
using (FileStream fileStream = new FileStream(localFilePath, FileMode.Create))
{
long totalLen = 0;
int contentLen = 0;
byte[] buff = new byte[BufLen];
while ((contentLen = await stream.ReadAsync(buff, 0, BufLen)) > 0)
{
await fileStream.WriteAsync(buff, 0, contentLen);
totalLen += contentLen;
if (EventDonwloadFileProgress != null && length > 0)
EventDonwloadFileProgress(totalLen, length, fileName);
}
}
} ret = true;
if (EventDonwloadResult != null)
EventDonwloadResult(ret, $@"{serverFilePath} : 下载成功!");
}
catch (Exception ex)
{
ret = false;
if (EventDonwloadResult != null)
EventDonwloadResult(ret, $@"{serverFilePath} : 下载失败!Exception : {ex.ToString()}");
}
finally
{
if (reqFtp != null)
reqFtp.Abort();
if (respFtp != null)
respFtp.Close();
} return ret;
} /// <summary>
/// 异步批量上传文件
/// </summary>
/// <param name="localFilePaths"></param>
public async void UploadFilesAsync(List<string> localFilePaths)
{
if (localFilePaths == null || localFilePaths.Count == 0)
return; int i = 1;
foreach (var localFilePath in localFilePaths)
{
await UploadFileAsync(localFilePath);
if (EventUploadBatchFilesProgress != null)
EventUploadBatchFilesProgress(i++, localFilePaths.Count);
}
} /// <summary>
/// 异步批量下载文件
/// </summary>
/// <param name="fileNames"></param>
/// <param name="localDirectory"></param>
public async void DownloadFilesAsync(List<FileModel> files, string localDirectory)
{
if (files == null || files.Count == 0 || string.IsNullOrEmpty(localDirectory))
return; int i = 1;
foreach (var file in files)
{
await DownloadFileAsync(file.Name, file.Size, localDirectory);
if (EventDonwloadBatchFilesProgress != null)
EventDonwloadBatchFilesProgress(i++, files.Count);
System.Threading.Thread.Sleep(1000);
}
} /// <summary>
/// 读取远程文件的内容
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
public string ReadFromFile(string serverFilePath)
{
if (string.IsNullOrEmpty(serverFilePath))
return ""; string ret = "";
FtpWebRequest reqFtp = null;
FtpWebResponse respFtp = null; try
{
//建立ftp连接
reqFtp = (FtpWebRequest)FtpWebRequest.Create(new Uri(serverFilePath));
reqFtp.UseBinary = true;
reqFtp.Credentials = new NetworkCredential(FtpUser, FtpPassword);
reqFtp.KeepAlive = false;
reqFtp.Method = WebRequestMethods.Ftp.DownloadFile; respFtp = reqFtp.GetResponse() as FtpWebResponse;
using (Stream stream = respFtp.GetResponseStream())
{
using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
{
ret = reader.ReadToEnd();
}
}
}
catch (Exception ex)
{
ret = "";
throw ex;
}
finally
{
if (reqFtp != null)
reqFtp.Abort();
if (respFtp != null)
respFtp.Close();
} return ret;
} /// <summary>
/// 读取远程文件的内容
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
public async Task<string> ReadFromFileAsync(string serverFilePath)
{
if (string.IsNullOrEmpty(serverFilePath))
return ""; string ret = "";
FtpWebRequest reqFtp = null;
FtpWebResponse respFtp = null; try
{
//建立ftp连接
reqFtp = (FtpWebRequest)FtpWebRequest.Create(new Uri(serverFilePath));
reqFtp.UseBinary = true;
reqFtp.Credentials = new NetworkCredential(FtpUser, FtpPassword);
reqFtp.KeepAlive = false;
reqFtp.Method = WebRequestMethods.Ftp.DownloadFile; respFtp = reqFtp.GetResponse() as FtpWebResponse;
using (Stream stream = respFtp.GetResponseStream())
{
using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
{
ret = await reader.ReadToEndAsync();
}
}
}
catch (Exception ex)
{
ret = "";
throw ex;
}
finally
{
if (reqFtp != null)
reqFtp.Abort();
if (respFtp != null)
respFtp.Close();
} return ret;
} #endregion
}

  

ftp上传文件和下载文件的更多相关文章

  1. Jenkins通过FTP上传站点太多文件导致太慢且不稳定,切换为压包上传再解压的思路(asp.net)

    在本地先处理好要上传的站点文件之后,可能会因为一些网页切图导致ftp上传不稳定,中断,或者文件占用的问题. 那么换了一种实现思路,要借助jenkins的工具jenkins-cli.jar. 解决思路: ...

  2. 批处理向FTP上传指定属性的文件 批处理增量备份的例子

    使用windows批处理向FTP上传具有指定属性的文件,类似增量备份功能. 对一个目录里的几个文件自动上传FTP时只上传有归档属性的文件,然后FTP上传成功后自动清除(本机)刚上传文件的归档属性. 类 ...

  3. 20160113006 asp.net实现ftp上传代码(解决大文件上传问题)

    using System;using System.Configuration;using System.Data;using System.Linq;using System.Web;using S ...

  4. Xshell 本地上传、远程下载文件

    1.Xshell登录工具在创建会话的时候,点击最下面的ZMODEM,可以填写下载的路径和加载的路径:2个路径可以一样也可以不一样: 在下载的时候可以下载到相应的路径去.(我设置的是下载前始终询问) 2 ...

  5. Selenium(十一):设置元素等待、上传文件、下载文件

    1. 设置元素等待 前面我们接触了几个元素等待方法,sleep.implicitly_wait方法,这一章我们就来整体学一下. 现在大多数Web应用程序使用的都是AJAX技术.当浏览器加载页面时,页面 ...

  6. ftp上传html文件

    在用ftp上传当个html文件时,发现html文件会被压缩成一行,在html中的单行注释将后面的代码都注释掉了,导致网页不能正常访问. 8uftp.FlashFXP.filezilla 在这三个ftp ...

  7. Java ftp 上传文件和下载文件

    今天同事问我一个ftp 上传文件和下载文件功能应该怎么做,当时有点懵逼,毕竟我也是第一次,然后装了个逼,在网上找了一段代码发给同事,叫他调试一下.结果悲剧了,运行不通过.(装逼失败) 我找的文章链接: ...

  8. ftp上传与下载文件

    准备工作 服务器已经配置好ftp服务 服务器linux centos 7.4 搭建ftp服务器:https://www.cnblogs.com/mmzs/p/10601683.html 需要用到的ja ...

  9. ftp上传或下载文件工具类

    FtpTransferUtil.java工具类,向ftp上传或下载文件: package utils; import java.io.File; import java.io.FileOutputSt ...

  10. java客户端调用ftp上传下载文件

    1:java客户端上传,下载文件. package com.li.utils; import java.io.File; import java.io.FileInputStream; import ...

随机推荐

  1. 用cmd命令加密文件夹

    比如新建一个叫“大学财务”的文件夹,我希望这个文件夹下的内容是加密隐藏的. 查看的时候需要点击“大学财务.bat”这个文件,然后输入设置的密码即可. Cls @ECHO OFF title Folde ...

  2. 学习笔记:CentOS7学习之二十一: 条件测试语句和if流程控制语句的使用

    目录 学习笔记:CentOS7学习之二十一: 条件测试语句和if流程控制语句的使用 21.1 read命令键盘读取变量的值 21.1.1 read常用见用法及参数 21.2 流程控制语句if 21.2 ...

  3. Java操作Excle(基于Poi)

    有一次有个同事问我会不会有java操作Excle,回答当然是不会了!感觉被嘲讽了,于是开始寻找度娘,找到个小例子,结果越写越有意思,最后就成就了这个工具类. import java.io.Buffer ...

  4. mysql插入中文数据变成问号怎么处理

    插入中文数据变成问号,一般都是因为字符集没有设置成utf8的原因 1.修改字符集: ALTER TABLE 表名 MODIFY 列名 类型(50) CHARACTER SET "utf8&q ...

  5. 【51nod】2591 最终讨伐

    [51nod]2591 最终讨伐 敲51nod是啥评测机啊,好几次都编译超时然后同一份代码莫名奇妙在众多0ms中忽然超时 这道题很简单就是\(M\)名既被诅咒也有石头的人,要么就把石头给没有石头被诅咒 ...

  6. Go-常识补充-切片-map(类似字典)-字符串-指针-结构体

    目录 Go 常识补充 Go 命名 打印变量类型科普 _ 关键字 命名规范相关 包目录规范 切片 多维切片 切片初始化的方法 多维切片初始化 切片删除元素(会略微影响效率 ,少用) copy 函数 打散 ...

  7. Ubuntu 提示sudo: java: command not found解决办法

    ubuntu下运行sudo Java 时提示“sudo: java: command not found”.在网上找了,其中很多方法都提示要修改/etc/profile的配置,或是修改/etc/env ...

  8. MySQL优化 - 性能分析与查询优化(转)

    出处:  MySQL优化 - 性能分析与查询优化 优化应贯穿整个产品开发周期中,比如编写复杂SQL时查看执行计划,安装MySQL服务器时尽量合理配置(见过太多完全使用默认配置安装的情况),根据应用负载 ...

  9. easyui-combobox多选时的小问题

    easyui-combobox可支持多选,仅需将multiple值设为true即可 $('#combobox').combobox({ url:url, multiple:true, separato ...

  10. MySQL - 性能优化 & MySQL常见SQL错误用法(转载)

    1. LIMIT 语句 分页查询是最常用的场景之一,但也通常也是最容易出问题的地方.比如: , ; 一般DBA想到的办法是在type, name, create_time字段上加组合索引.这样条件排序 ...