帮助类:

using QSProjectBase;
using Reform.CommonLib;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text; namespace Reform.CommonLib
{
/// <summary>
/// ftp操作
/// </summary>
public class FtpHelper
{
/// <summary>
/// 上传文件
/// </summary>
/// <param name="fileName">上传文件的全路径</param>
/// <param name="accessory">上传类</param>
/// <returns></returns>
public static bool UploadFile(FileInfo fileinfo, string ftpPath)
{
try
{
if (fileinfo == null || string.IsNullOrEmpty(ftpPath))
return false; string url = ftpPath;
if (url.Contains("/") || url.Contains("\\"))
{
var str = url.Split(new Char[] { '/', '\\' });
var dic = url.Replace(str[str.Length - ], "");
CheckAndMakeDir(dic);
} System.Net.FtpWebRequest ftp = GetRequest(url); //设置FTP命令 设置所要执行的FTP命令,
//ftp.Method = System.Net.WebRequestMethods.Ftp.ListDirectoryDetails;//假设此处为显示指定路径下的文件列表
ftp.Method = System.Net.WebRequestMethods.Ftp.UploadFile;
ftp.UseBinary = true;
ftp.UsePassive = true;
ftp.ContentLength = fileinfo.Length; const int BufferSize = ; //缓冲大小设置为20KB
byte[] content = new byte[BufferSize - + ];
int dataRead; using (FileStream fs = fileinfo.OpenRead())
{
try
{
using (Stream rs = ftp.GetRequestStream())
{
do
{
dataRead = fs.Read(content, , BufferSize);
rs.Write(content, , dataRead);
} while (!(dataRead < BufferSize));
rs.Close();
}
}
catch (Exception) { }
finally
{
fs.Close();
}
}
ftp = null;
////设置FTP命令
//ftp = GetRequest(URI);
//ftp.Method = System.Net.WebRequestMethods.Ftp.Rename; //改名
//ftp.RenameTo = fileinfo.Name;
//try
//{
// ftp.GetResponse();
//}
//catch (Exception ex)
//{
// ftp = GetRequest(URI);
// ftp.Method = System.Net.WebRequestMethods.Ftp.DeleteFile; //删除
// ftp.GetResponse();
//}
//ftp = null;
return true;
}
catch (Exception)
{
return false;
}
} /// <summary>
/// 上传文件
/// </summary>
/// <param name="fileName">上传文件的全路径</param>
/// <param name="ftpPath">上传的目录(包括文件名)</param>
/// <param name="progressHelper">进度帮助</param>
/// <returns></returns>
public static bool UploadFile(FileInfo fileinfo, string ftpPath, ProgressHelper progressHelper, MessageProgressHandler handler)
{
try
{
if (fileinfo == null || string.IsNullOrEmpty(ftpPath))
return false; string url = ftpPath;
if (url.Contains("/") || url.Contains("\\"))
{
var str = url.Split(new Char[] { '/', '\\' });
var dic = url.Replace(str[str.Length - ], "");
CheckAndMakeDir(dic);
}
System.Net.FtpWebRequest ftp = GetRequest(url); //设置FTP命令 设置所要执行的FTP命令,
//ftp.Method = System.Net.WebRequestMethods.Ftp.ListDirectoryDetails;//假设此处为显示指定路径下的文件列表
ftp.Method = System.Net.WebRequestMethods.Ftp.UploadFile;
ftp.UseBinary = true;
ftp.UsePassive = false;
ftp.ContentLength = fileinfo.Length; const int BufferSize = ; //缓冲大小设置为20KB
byte[] content = new byte[BufferSize - + ];
int dataRead; using (FileStream fs = fileinfo.OpenRead())
{
long fileLen = fs.Length;
if (progressHelper != null && handler != null)
{
progressHelper.SetProgress(handler, "正在上传...", );
}
try
{
long proValue = ;
using (Stream rs = ftp.GetRequestStream())
{ do
{
dataRead = fs.Read(content, , BufferSize);
rs.Write(content, , dataRead);
proValue += dataRead;
if (progressHelper != null && handler != null)
{
progressHelper.SetProgress(handler, "正在上传...", (int)((double)proValue * / fileLen));
}
} while (!(dataRead < BufferSize));
var aa = rs.Length;
rs.Close();
}
}
catch (Exception) { }
finally
{
fs.Close();
}
}
ftp = null;
////设置FTP命令
//ftp = GetRequest(URI);
//ftp.Method = System.Net.WebRequestMethods.Ftp.Rename; //改名
//ftp.RenameTo = fileinfo.Name;
//try
//{
// ftp.GetResponse();
//}
//catch (Exception ex)
//{
// ftp = GetRequest(URI);
// ftp.Method = System.Net.WebRequestMethods.Ftp.DeleteFile; //删除
// ftp.GetResponse();
//}
//ftp = null;
return true;
}
catch (Exception)
{
return false;
}
} /// <summary>
/// 下载文件
/// </summary>
/// <param name="localDir">下载到本地(全路径)</param>
/// <param name="accessory">要下载的附件类</param>
public static bool DownloadFile(string localFilePath, string ftpPath)
{
if (string.IsNullOrEmpty(ftpPath)) return false;
if (string.IsNullOrEmpty(localFilePath)) return false;
System.Net.FtpWebRequest ftp = null;
try
{
string Url = ftpPath;
string localDir = new FileInfo(localFilePath).DirectoryName;
if (!Directory.Exists(localDir))
{
Directory.CreateDirectory(localDir);
}
string tmpname = Guid.NewGuid().ToString();
string tmpFilePath = localDir + @"\" + tmpname; ftp = GetRequest(Url);
// MsgBoxShow.ShowInformation(Url);
ftp.Method = System.Net.WebRequestMethods.Ftp.DownloadFile;
ftp.UseBinary = true;
ftp.UsePassive = false; using (FtpWebResponse response = (FtpWebResponse)ftp.GetResponse())
{
using (Stream responseStream = response.GetResponseStream())
{
using (FileStream fs = new FileStream(tmpFilePath, FileMode.CreateNew))
{
var aa = ftp.ContentLength;
try
{
byte[] buffer = new byte[];
int read = ;
do
{
read = responseStream.Read(buffer, , buffer.Length);
fs.Write(buffer, , read);
} while (!(read == ));
responseStream.Close();
fs.Flush();
fs.Close();
}
catch (Exception)
{
fs.Close();
File.Delete(tmpFilePath);
return false;
}
}
responseStream.Close();
}
response.Close();
}
try
{
File.Delete(localFilePath);
File.Move(tmpFilePath, localFilePath);
ftp = null;
}
catch (Exception)
{
File.Delete(tmpFilePath);
return false;
}
ftp = null;
return true;
}
catch (WebException e)
{
Common_LogManager.RecordLog(LogType.Error, e.Message, e);
if (e.Status == WebExceptionStatus.ProtocolError)
{
Console.WriteLine("Status Code : {0}", ((FtpWebResponse)e.Response).StatusCode);
Console.WriteLine("Status Description : {0}", ((FtpWebResponse)e.Response).StatusDescription);
}
return false;
}
} /// <summary>
/// 下载文件,叠加
/// </summary>
/// <param name="localDir">下载到本地(全路径)</param>
/// <param name="accessory">要下载的附件类</param>
public static bool DownloadFileEx(string localFilePath, string ftpPath)
{
if (string.IsNullOrEmpty(ftpPath)) return false;
if (string.IsNullOrEmpty(localFilePath)) return false;
try
{
string Url = ftpPath; System.Net.FtpWebRequest ftp = GetRequest(Url);
ftp.Method = System.Net.WebRequestMethods.Ftp.DownloadFile;
ftp.UseBinary = true;
ftp.UsePassive = false; using (FtpWebResponse response = (FtpWebResponse)ftp.GetResponse())
{
using (Stream responseStream = response.GetResponseStream())
{
using (FileStream fs = new FileStream(localFilePath, FileMode.Append))
{
try
{
byte[] buffer = new byte[];
int read = ;
do
{
read = responseStream.Read(buffer, , buffer.Length);
fs.Write(buffer, , read);
} while (!(read == ));
responseStream.Close();
fs.Flush();
fs.Close();
}
catch (Exception)
{
fs.Close();
return false;
}
}
responseStream.Close();
}
response.Close();
}
try
{
ftp = null;
}
catch (Exception)
{
return false;
}
ftp = null;
return true;
}
catch (Exception)
{
return false;
}
} /// <summary>
/// 下载文件(包含进度)
/// </summary>
/// <param name="localDir">下载到本地(全路径)</param>
/// <param name="accessory">要下载的附件类</param>
public static bool DownloadFile(string localFilePath, string ftpPath, ProgressHelper progressHelper, MessageProgressHandler handler)
{
if (string.IsNullOrEmpty(ftpPath)) return false;
if (string.IsNullOrEmpty(localFilePath)) return false; try
{
string URI = ftpPath;
string localDir = new FileInfo(localFilePath).DirectoryName; string tmpname = Guid.NewGuid().ToString();
string tmpFilePath = localDir + @"\" + tmpname; System.Net.FtpWebRequest ftp = GetRequest(URI);
ftp.Method = System.Net.WebRequestMethods.Ftp.DownloadFile;
ftp.UseBinary = true;
ftp.UsePassive = false;
long fileLen = GetFileSize(ftpPath);
using (WebResponse response = ftp.GetResponse())
{
using (Stream responseStream = response.GetResponseStream())
{
if (progressHelper != null && handler != null)
{
progressHelper.SetProgress(handler, "正在下载...", );
}
using (FileStream fs = new FileStream(tmpFilePath, FileMode.OpenOrCreate))
{
try
{
long proValue = ;
byte[] buffer = new byte[];
int read = ;
do
{
read = responseStream.Read(buffer, , buffer.Length);
fs.Write(buffer, , read);
proValue += read;
if (progressHelper != null && handler != null)
{
progressHelper.SetProgress(handler, "正在下载...", (int)((double)proValue * / fileLen));
}
} while (!(read == ));
responseStream.Close();
fs.Flush();
fs.Close();
}
catch (Exception)
{
fs.Close();
File.Delete(tmpFilePath);
return false;
}
}
responseStream.Close();
}
response.Close();
}
try
{
File.Delete(localFilePath);
File.Move(tmpFilePath, localFilePath);
ftp = null;
}
catch (Exception ex)
{
File.Delete(tmpFilePath);
return false;
}
ftp = null;
return true;
}
catch (Exception)
{
return false;
}
} /// <summary>
/// 删除文件
/// </summary>
/// <param name="accessory">要删除的附件全路径</param>
public static bool DeleteFile(string ftpPath)
{
if (string.IsNullOrEmpty(ftpPath)) return false;
try
{
string URI = ftpPath;
System.Net.FtpWebRequest ftp = GetRequest(URI);
ftp.Method = System.Net.WebRequestMethods.Ftp.DeleteFile;
ftp.UseBinary = true;
ftp.UsePassive = false;
using (FtpWebResponse response = (FtpWebResponse)ftp.GetResponse())
{
using (Stream responseStream = response.GetResponseStream())
{
responseStream.Close();
}
response.Close();
}
ftp = null;
return true;
}
catch (Exception)
{
return false;
}
} /// <summary>
/// 搜索远程文件
/// </summary>
/// <param name="targetDir">文件夹</param>
/// <param name="SearchPattern">搜索模式</param>
/// <returns></returns>
public static List<string> ListDirectory(string targetDir, string SearchPattern)
{
List<string> result = new List<string>();
try
{
string URI = targetDir + "/" + SearchPattern;
System.Net.FtpWebRequest ftp = GetRequest(URI);
ftp.Method = System.Net.WebRequestMethods.Ftp.ListDirectory;
ftp.UsePassive = true;
ftp.UseBinary = true; string str = GetStringResponse(ftp);
str = str.Replace("\r\n", "\r").TrimEnd('\r');
str = str.Replace("\n", "\r");
if (str != string.Empty)
result.AddRange(str.Split('\r')); return result;
}
catch { }
return null;
} private static string GetStringResponse(FtpWebRequest ftp)
{
string result = "";
using (FtpWebResponse response = (FtpWebResponse)ftp.GetResponse())
{
long size = response.ContentLength;
using (Stream datastream = response.GetResponseStream())
{
using (StreamReader sr = new StreamReader(datastream, System.Text.Encoding.Default))
{
result = sr.ReadToEnd();
sr.Close();
} datastream.Close();
} response.Close();
} return result;
} public static void CheckAndMakeDir(string dirName)
{
if (string.IsNullOrEmpty(dirName))
{
return;
}
if (dirName.Contains("/") || dirName.Contains("\\"))
{
var str = dirName.Split(new Char[] { '/', '\\' });
if (str.Length == || string.IsNullOrEmpty(str[]))
{
return;
}
string dir = str[] + "/";
if (!IsExistsFile(dir))
MakeDir(dir);
for (int i = ; i < str.Length; i++)
{
if (string.IsNullOrEmpty(str[i]))
{
continue;
}
dir += (str[i] + "/");
if (!IsExistsFile(dir))
MakeDir(dir);
} }
else
{
if (!IsExistsFile(dirName))
MakeDir(dirName);
}
}
///
/// 在ftp服务器上创建目录
/// </summary>
/// <param name="dirName">创建的目录名称</param>
public static void MakeDir(string dirName)
{
try
{
System.Net.FtpWebRequest ftp = GetRequest(dirName);
ftp.Method = WebRequestMethods.Ftp.MakeDirectory; FtpWebResponse response = (FtpWebResponse)ftp.GetResponse();
response.Close();
}
catch (Exception ex)
{
//MessageBox.Show(ex.Message);
}
} /// <summary>
/// 删除目录
/// </summary>
/// <param name="dirName">删除目录名称</param>
public static bool delDir(string dirName)
{
try
{
System.Net.FtpWebRequest ftp = GetRequest(dirName);
ftp.Method = WebRequestMethods.Ftp.RemoveDirectory;
FtpWebResponse response = (FtpWebResponse)ftp.GetResponse();
response.Close();
return true;
}
catch (Exception ex)
{
return false;
}
}
/// <summary>
/// 文件重命名
/// </summary>
/// <param name="currentFilename">当前目录名称</param>
/// <param name="newFilename">重命名目录名称</param>
public static bool Rename(string currentFilename, string newFilename)
{
try
{
FileInfo fileInf = new FileInfo(currentFilename);
System.Net.FtpWebRequest ftp = GetRequest(fileInf.Name);
ftp.Method = WebRequestMethods.Ftp.Rename; ftp.RenameTo = newFilename;
FtpWebResponse response = (FtpWebResponse)ftp.GetResponse(); response.Close();
return true;
}
catch (Exception ex)
{
return false;
}
} private static FtpWebRequest GetRequest(string dirName)
{
string url = "ftp://" + ConfigHepler.FtpServer + "/" + dirName;
//根据服务器信息FtpWebRequest创建类的对象
FtpWebRequest result = (FtpWebRequest)FtpWebRequest.Create(url);
//提供身份验证信息
result.Credentials = new System.Net.NetworkCredential(ConfigHepler.FtpUser, ConfigHepler.FtpPwd);
//设置请求完成之后是否保持到FTP服务器的控制连接,默认值为true
result.KeepAlive = false; return result;
} /// <summary>
/// 判断ftp服务器上该目录是否存在
/// </summary>
/// <param name="dirName"></param>
/// <returns></returns>
public static bool IsExistsFile(string dirName)
{
bool flag = true;
try
{
System.Net.FtpWebRequest ftp = GetRequest(dirName);
ftp.Method = WebRequestMethods.Ftp.ListDirectory; FtpWebResponse response = (FtpWebResponse)ftp.GetResponse();
response.Close();
}
catch (Exception)
{
flag = false;
}
return flag;
} // 获取文件大小
public static long GetFileSize(string ftpPath)
{
long size = ;
if (string.IsNullOrEmpty(ftpPath)) return size;
try
{
string URI = ftpPath; System.Net.FtpWebRequest ftp = GetRequest(URI);
ftp.Method = System.Net.WebRequestMethods.Ftp.GetFileSize;
ftp.UseBinary = true;
ftp.UsePassive = false; using (FtpWebResponse response = (FtpWebResponse)ftp.GetResponse())
{ size = response.ContentLength; } }
catch (Exception)
{ }
return size;
} } /// <summary>
/// 从配置文件获取配置信息
/// </summary>
public class ConfigHepler
{
private static string m_FtpServer;
private static string m_FtpUser;
private static string m_FtpPwd;
/// <summary>
/// ftp服务器
/// </summary>
public static string FtpServer
{
get
{
if (string.IsNullOrEmpty(m_FtpServer))
{
string[] ftpConfigs = GlobalVars.FtpConfig.Split(new char[] { ';' });
if (ftpConfigs != null && ftpConfigs.Length > )
m_FtpServer = ftpConfigs[];
} return m_FtpServer;
}
} /// <summary>
/// ftp用户名
/// </summary>
public static string FtpUser
{
get
{
if (string.IsNullOrEmpty(m_FtpUser))
{
string[] ftpConfigs = GlobalVars.FtpConfig.Split(new char[] { ';' });
if (ftpConfigs != null && ftpConfigs.Length > )
m_FtpUser = ftpConfigs[];
} return m_FtpUser;
}
} /// <summary>
/// ftp密码
/// </summary>
public static string FtpPwd
{
get
{
if (string.IsNullOrEmpty(m_FtpPwd))
{
string[] ftpConfigs = GlobalVars.FtpConfig.Split(new char[] { ';' });
if (ftpConfigs != null && ftpConfigs.Length > )
m_FtpPwd = ftpConfigs[];
} return m_FtpPwd;
}
}
} }

配置文件配置:

<!--ftp配置,以分号相隔 格式:"主机名;用户名;密码;"-->
例子:<Item key="FtpConfig" value="192.168.0.1;admin;123456" />

上传调用例子:

FileInfo fInfo = new FileInfo(txtDoc.Text);
//上传到ftp的完整目录,FTP目录+文件格式+日期+GUID+文件名+文件后缀
ftpPath = M_FTPDIRECTORY + m_Archives.DocType.Replace(".", "") + "/" + DateTime.Now.ToString("yyyyMMdd") + "/" + Guid.NewGuid().ToString() + "/" + m_Archives.DocName + m_Archives.DocType;
bool suc = FtpHelper.UploadFile(fInfo, ftpPath);

FTP文件上传以及获取ftp配置帮助类的更多相关文章

  1. FTP文件上传

    一.配置FTP文件服务器 以Ubuntu为例 FTP两种模式简介 PORT(主动模式) 第一步FTP客户端首先随机选择一个大于1024的端口p1,并通过此端口发送请求连接到FTP服务器的21号端口建立 ...

  2. 基于SqlSugar的开发框架循序渐进介绍(7)-- 在文件上传模块中采用选项模式【Options】处理常规上传和FTP文件上传

    在基于SqlSugar的开发框架的服务层中处理文件上传的时候,我们一般有两种处理方式,一种是常规的把文件存储在本地文件系统中,一种是通过FTP方式存储到指定的FTP服务器上.这种处理应该由程序进行配置 ...

  3. Java实现FTP文件上传与下载

    实现FTP文件上传与下载可以通过以下两种种方式实现(不知道还有没有其他方式),分别为:1.通过JDK自带的API实现:2.通过Apache提供的API是实现. 第一种方式 package com.cl ...

  4. Python 基于Python实现Ftp文件上传,下载

    基于Python实现Ftp文件上传,下载   by:授客 QQ:1033553122 测试环境: Ftp客户端:Windows平台 Ftp服务器:Linux平台 Python版本:Python 2.7 ...

  5. Java使用comms-net jar包完成ftp文件上传进度的检测功能

    本文章只讲述大致的思路与本次功能对应的一些开发环境,具体实现请结合自己的开发情况,仅供参考,如果有不对的地方,欢迎大家指出! 准备环境:JDK1.7 OR 1.8.eclipse.ftp服务器(可自行 ...

  6. java/struts/Servlet文件下载与ftp文件上传下载

    1.前端代码 使用超链接到Struts的Action或Servlet <a target="_blank" href="ftpFileAction!download ...

  7. FTP文件上传并支持断点续传(一)—— win10 本地环境 ftp站点构建

    由于之前项目开发是采用是采用的FTP文件上传,就一直想学习,但由于FTP服务器是公司的,为了方便就像把本地变成ftp站点,其实很简单,但也有很多坑 这里简单介绍一下自己遇到的坑 一:开通本地的ftp权 ...

  8. struts 多文件上传 annotation注解(零配置)+ ajaxfileupload + 异步 版本

    [本文简介] struts 多文件上传.基于”零配置“+"ajaxfileupload" 的一个简单例子. [导入依赖jar包] jquery-1.7.2.js : http:// ...

  9. struts文件上传,获取文件名和文件类型

    struts文件上传,获取文件名和文件类型   Action中还有两个属 性:uploadFileName和uploadContentType,这两个属性分别用于封装上传文件的文件名.文件类型.这是S ...

随机推荐

  1. java动态画圈圈。运用多线程,绘图

    总结:只是意外的收获吧.之前一篇是老师教的,一个点,从底层开始升起,到鼠标按下的地方开始画圈圈, 现在改变了一下,因为点上升的一个循环和画圈的循环是分开的 现在让点点自己跑,并且边跑边画圈.而且在fo ...

  2. PHP判断文件是否被引入的方法get_included_files

    <?php // 本文件是 abc.php include 'test1.php'; include_once 'test2.php'; require 'test3.php'; require ...

  3. 爬了个爬(三)Scrapy框架

    参考博客:武Sir Scrapy是一个为了爬取网站数据,提取结构性数据而编写的应用框架. 其可以应用在数据挖掘,信息处理或存储历史数据等一系列的程序中.其最初是为了页面抓取 (更确切来说, 网络抓取 ...

  4. AJAX的流程是什么?

    客户端产生js的事件 创建XMLHttpRequest对象 对XMLHttpRequest进行配置 通过AJAX引擎发送异步请求 服务器端接受请求并且处理请求,返回html或者xml内容 XML调用一 ...

  5. python对裤子进行一个查询

    前言: 获取到一个数据库,使用python对其 进简单的查询 代码: import time print('开房记录查询') def chax(): g=input('请输入要查询的>>& ...

  6. pandas层级索引1

    层级索引(hierarchical indexing) 下面创建一个Series, 在输入索引Index时,输入了由两个子list组成的list,第一个子list是外层索引,第二个list是内层索引. ...

  7. Centos7下快速安装Mongo3.2

    Centos7下快速安装Mongo3.2 一般安装Mongo推荐源码安装,有时候为了快部署测试环境,或者仅仅是想装个mongo shell,这时候yum安装是最合适的方式, 下面介绍一下如何在Cent ...

  8. In function 'int av_clipl_int32_c(int64_t)': error: 'UINT64_C' was not declared in this scope

    cygwin下使用ndk编译jni时遇到的错误: /ffmpeg/include/libavutil/common.h: In function 'int av_clipl_int32_c(int64 ...

  9. 19-EasyNetQ:用EasyNetQ.Hosepipe重新提交错误信息

    EasyNetQ.Hosepipe是EasyNetQ队列管理工具.用来取回队列中的消息并重新发布这些消息.还可以用它来检测错误队列,并重试发布消息. 用法 EasyNetQ.Hosepipe.exe ...

  10. 6410在rvds下编译启动代码报错分析

    contains invalid call from '~PRES8' function to 'REQ8' function main RVDS编译出现contains invalid call f ...