首页 > 代码库 > ftp操作类

ftp操作类

在项目中,结合网上找的几份资料,综合整理了一份ftp上传,下载,ftp上选择文件上传到另外一个ftp的资料,注:本类中所有路径都是完整路径。

using System;
using System.Net;
using System.IO;
using Glorysoft.RMS.Client.Controllers;

namespace UpLoad
{
public class ftpCopy
{
private string ftpUser; //ftp用户名
private string ftpPassword; //ftp密码

public ftpCopy(string ftpUser,string ftpPassword) {
this.ftpUser = ftpUser;
this.ftpPassword = ftpPassword;
}

/// <summary>
/// 上传文件
/// </summary>
/// <param name="localFile1">本地文件路径及文件名</param>
/// <param name="ftpFileName">ftp文件路径及文件名(文件名可重命名)</param>
/// <returns>返回bool值</returns>
public bool fileUpload(string localFile1, string ftpFileName)
{
FileInfo localFile = new FileInfo(localFile1);
bool success = false;
FtpWebRequest ftpWebRequest = null;
FileStream localFileStream = null;
Stream requestStream = null;
TimeSpanClass timeSp = new TimeSpanClass();
string strFtp=string.Empty;
string strZip = string.Empty;
string strFtpAndZip = string.Empty;

// 开始上传处理
//string templateFileName = Path.Combine(HttpContext.Current.Server.MapPath("."), "index.cshtml");
//StreamReader reader = new StreamReader(@templateFileName, System.Text.Encoding.GetEncoding("gb2312"));

// 根据处理任务处理情况更新进度条
try
{
string uri = ftpFileName;
ftpWebRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
ftpWebRequest.Credentials = new NetworkCredential(ftpUser, ftpPassword);
ftpWebRequest.UseBinary = true; //指定数据传输类型为二进制
ftpWebRequest.KeepAlive = false; //成功执行一个命令后连接被关闭
ftpWebRequest.Method = WebRequestMethods.Ftp.UploadFile; // 指定执行什么命令
ftpWebRequest.ContentLength = localFile.Length; //上传文件时通知服务器文件的大小
int buffLength = 1024*1024; // 缓冲大小设置为1kb*1kb
byte[] buff = new byte[buffLength];
int contentLen;
localFileStream = localFile.OpenRead(); //打开一个文件流去读上传的文件
requestStream = ftpWebRequest.GetRequestStream(); //把上传的文件写入流
contentLen = localFileStream.Read(buff, 0, buffLength); //每次读文件流的1kb*1kb

long len = 0;

while (contentLen != 0)//流内容没有结束
{
len += contentLen;

// 把内容从file stream 写入 upload stream
requestStream.Write(buff, 0, contentLen);
contentLen = localFileStream.Read(buff, 0, buffLength);

//设置进度条
long ps = (len * 100)/ localFileStream.Length;
string pos = ps.ToString();
// int i = Convert.ToInt32((len * 100) / localFileStream.Length);
RecipeUploadController.progressBar = pos;
}

}
catch (Exception)
{
success = false;
}
finally
{
//结束进度条
RecipeUploadController recp = new RecipeUploadController();
RecipeUploadController.progressBar = 100.ToString();

System.Threading.Thread.Sleep(3000);
RecipeUploadController.progressBar = 0.ToString();


//System.Threading.Thread.Sleep(3000);

if (requestStream != null)
{
requestStream.Close();
}
if (localFileStream != null)
{
localFileStream.Close();
}
}
return success;
}

/// 从ftp下载文件到本地服务器
/// </summary>
/// <param name="downloadUrl">要下载的ftp文件路径,如ftp://192.168.1.104/capture-2.avi</param>
/// <param name="saveFileUrl">本地保存文件的路径,如(@"d:\capture-22.avi"</param>
public void fileDownload(string downloadUrl, string saveFileUrl)
{
Stream responseStream = null;
FileStream fileStream = null;
StreamReader reader = null;

try
{
// string downloadUrl = "ftp://192.168.1.104/capture-2.avi";

FtpWebRequest downloadRequest = (FtpWebRequest)WebRequest.Create(downloadUrl);
downloadRequest.Method = WebRequestMethods.Ftp.DownloadFile;

//string ftpUser = "yoyo";
//string ftpPassWord = "123456";
downloadRequest.Credentials = new NetworkCredential(ftpUser, ftpPassword);

FtpWebResponse downloadResponse = (FtpWebResponse)downloadRequest.GetResponse();
responseStream = downloadResponse.GetResponseStream();

fileStream = File.Create(saveFileUrl);
byte[] buffer = new byte[1024];
int bytesRead;
while (true)
{
bytesRead = responseStream.Read(buffer, 0, buffer.Length);
if (bytesRead == 0)
break;
fileStream.Write(buffer, 0, bytesRead);
}
}
catch (Exception ex)
{
throw new Exception("从ftp服务器下载文件出错,文件名:" + downloadUrl + "异常信息:" + ex.ToString());
}
finally
{
if (reader != null)
{
reader.Close();
}
if (responseStream != null)
{
responseStream.Close();
}
if (fileStream != null)
{
fileStream.Close();
}
}
}

 

/// <summary>
/// 从ftp上选择文件上传到另外一个ftp;
/// </summary>
/// <param name="downloadUrl">要下载的ftp文件路径,如ftp://192.168.1.104/capture-2.avi</param>
/// <param name="saveFileUrl">本地保存文件的路径,如(@"d:\capture-22.avi"</param>
/// <param name = "newUser">目标ftp用户名</param>
public void FtpToFtp(string downloadUrl, string saveFileUrl, string newUser, string newPwd)
{
Stream responseStream = null;
// FileStream fileStream = null;
StreamReader reader = null;
//FileInfo localFile = new FileInfo(saveFileUrl);
// bool success = false;
FtpWebRequest ftpWebRequest = null;
Stream requestStream = null;
TimeSpanClass timeSp = new TimeSpanClass();
string strFtp = string.Empty;
string strZip = string.Empty;
string strFtpAndZip = string.Empty;

 

//加载进度条
DateTime startTotalTimeFtp = System.DateTime.Now;
DateTime endTotalTimeFtp = System.DateTime.Now;

try
{
// string downloadUrl = "ftp://192.168.1.104/capture-2.avi";

FtpWebRequest downloadRequest = (FtpWebRequest)WebRequest.Create(downloadUrl);
downloadRequest.Method = WebRequestMethods.Ftp.DownloadFile;

//string ftpUser = "yoyo";
//string ftpPassWord = "123456";
downloadRequest.Credentials = new NetworkCredential(ftpUser, ftpPassword);

FtpWebResponse downloadResponse = (FtpWebResponse)downloadRequest.GetResponse();
long contentLength = getFileSize(downloadUrl); //获取上传文件的大小。
responseStream = downloadResponse.GetResponseStream();


//向另外一个ftp上传
string uri = saveFileUrl;
ftpWebRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
ftpWebRequest.Credentials = new NetworkCredential(newUser, newPwd);
ftpWebRequest.UseBinary = true; //指定数据传输类型为二进制
ftpWebRequest.KeepAlive = false; //成功执行一个命令后连接被关闭
ftpWebRequest.Method = WebRequestMethods.Ftp.UploadFile; // 指定执行什么命令
ftpWebRequest.ContentLength = contentLength; //上传文件时通知服务器文件的大小
int buffLength = 1024 * 1024; // 缓冲大小设置为1kb*1kb
byte[] buff = new byte[buffLength];
int contentLen;
requestStream = ftpWebRequest.GetRequestStream(); //把上传的文件写入流
contentLen = responseStream.Read(buff, 0, buffLength); //每次读文件流的1kb*1kb

long len = 0;

while (contentLen != 0)//流内容没有结束
{
len += contentLen;

// 把内容从file stream 写入 upload stream
requestStream.Write(buff, 0, contentLen);
contentLen = responseStream.Read(buff, 0, buffLength);

//设置进度条
long ps = (len * 100) / contentLength;
string pos = ps.ToString();
// int i = Convert.ToInt32((len * 100) / localFileStream.Length);
RecipeUploadController.progressBar = pos;

}

}
catch (Exception ex)
{
throw new Exception("从ftp服务器下载文件出错,文件名:" + downloadUrl + "异常信息:" + ex.ToString());
}
finally
{
if (reader != null)
{
reader.Close();
}
if (responseStream != null)
{
responseStream.Close();
}
if (requestStream != null)
{
requestStream.Close();
}
}
}

/// <summary>
/// 获取 ftp的文件的长度
/// </summary>
/// <param name="path">文件路径</param>
/// <returns></returns>
public long getFileSize(string path)
{
try
{
FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(path));
reqFTP.Method = WebRequestMethods.Ftp.GetFileSize;
reqFTP.Credentials = new NetworkCredential(ftpUser, ftpPassword);
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
long cl = response.ContentLength;
response.Close();
return cl;
}
catch (Exception ex)
{
return -1;
}
}
}
}

ftp操作类