public class FTPHelper
{
#region 字段
string ftpURI;
string ftpUserID;
string ftpServerIP;
string ftpPassword;
#endregion
///
/// 连接FTP服务器
///
/// FTP连接地址
/// 指定FTP连接成功后的当前目录, 如果不指定即默认为根目录
/// 用户名
/// 密码
public FTPHelper(string FtpServerIP, string FtpUserID, string FtpPassword)
{
ftpServerIP = FtpServerIP;
ftpUserID = FtpUserID;
ftpPassword = FtpPassword;
ftpURI = ftpServerIP + “/”;
}
/// <summary>
/// 上传
/// </summary>
public void Upload(string srcFilename, string destFtp, bool enalbeSsl = false)
{
FileInfo fileInf = new FileInfo(srcFilename);
string legalDestFtp = this.getLegalName(destFtp);
FtpWebRequest reqFTP = (FtpWebRequest)WebRequest.Create(new Uri(ftpURI + legalDestFtp));
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
reqFTP.KeepAlive = false;
reqFTP.UseBinary = true;
reqFTP.ContentLength = fileInf.Length;
reqFTP.EnableSsl = enalbeSsl;
int buffLength = 2048;
byte[] buff = new byte[buffLength];
int contentLen;
try
{
using (FileStream fs = fileInf.OpenRead())
{
using (Stream strm = reqFTP.GetRequestStream())
{
contentLen = fs.Read(buff, 0, buffLength);
while (contentLen != 0)
{
strm.Write(buff, 0, contentLen);
contentLen = fs.Read(buff, 0, buffLength);
}
strm.Close();
fs.Close();
}
}
}
catch (WebException ex)
{
throw ex;
}
catch (Exception e)
{
throw e;
}
}
#region 目录存在判断
#region new
/// <summary>
/// 判断ftp服务器上目录是否存在
/// </summary>
/// <param name="dir"></param>
/// <returns></returns>
public bool DirExsit(string dir, bool enalbeSsl = false)
{
string[] dirs = GetDirListCascade(dir);//获取待判断目录的级联父目录
//依次判断各个父目录是否存在
string curretDir = "";
for (int i = 0; i < dirs.Length; i++)
{
string levDir = dirs[i];
string onlyDir;//只有目录名
if (i == 0)
{
onlyDir = levDir;
}
else
{
onlyDir = levDir.Replace(curretDir, string.Empty).Replace("/", string.Empty).Replace("\\", string.Empty);
}
if (this.DirExit(onlyDir, curretDir,enalbeSsl))
{
curretDir = levDir;
continue;
}
return false;
}
return true;
}
/// <summary>
/// 目录是否在父目录存在
/// <para>前置条件,estimateDir目录和父目录是父子关系</para>
/// <para>前置条件,父目录存在</para>
/// <para>前置条件,estimateDir目录只是目录名,不包括路径</para>
/// </summary>
/// <param name="estimateDir"></param>
/// <param name="parentDir"></param>
/// <returns></returns>
private bool DirExit(string estimateDir, string parentDir, bool enalbeSsl = false)
{
string[] dirs = this.GetDirList(parentDir,enalbeSsl);
return dirs.Contains(estimateDir);
}
/// <summary>
/// 获取当前目录下文件夹列表(不包括文件)
/// </summary>
public string[] GetDirList(string url,bool enalbeSsl = false)
{
List<string> files = new List<string>();
string legaleName = this.getLegalName(url);
FtpWebRequest reqFTP;
try
{
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(this.ftpURI + legaleName));
reqFTP.UseBinary = true;
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
reqFTP.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
reqFTP.EnableSsl = enalbeSsl;
WebResponse response = reqFTP.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
string line = reader.ReadLine();
while (line != null)
{
if (line.IndexOf("<DIR>") != -1)
{
files.Add(Regex.Match(line, @"<DIR>\s+([\S]+)", RegexOptions.IgnoreCase).Groups[1].Value);
}
line = reader.ReadLine();
}
reader.Close();
response.Close();
}
catch (Exception ex)
{
throw (ex);
}
return files.ToArray();
}
/// <summary>
/// 获取最靠近该目录字符串的目录
/// <para>编写该函数的原因是用户书写ftp路径不规范,混乱使用"/" 和"\"</para>
/// </summary>
/// <param name="fullDir"></param>
/// <returns></returns>
private static string GetFirstDir(string fullDir)
{
string firstDir = fullDir;
if (fullDir.EndsWith(@"\"))
{
firstDir = Path.GetDirectoryName(fullDir);
}
if (fullDir.EndsWith(@"/"))
{
firstDir = Path.GetDirectoryName(fullDir);
}
return firstDir;
}
#endregion
public void MakeDirCascade(string dir, bool enalbeSsl = false)
{
string[] dirList = GetDirListCascade(dir);
for (int i = 0; i < dirList.Length; i++)
{
string chidDir = dirList[i];
try
{
this.MakeDir(chidDir,enalbeSsl);
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
}
/// <summary>
/// 获取级联目录
/// <para>目录11/22的级联目录是11和11/22</para>
/// <para>包含自身</para>
/// <para>如果是根目录下一级目录,则返回自身</para>
/// </summary>
/// <param name="fullDir"></param>
/// <returns></returns>
private static string[] GetDirListCascade(string fullDir)
{
List<string> dirList = new List<string>();
if (fullDir == null)
{
throw new ArgumentNullException();
}
if (string.IsNullOrWhiteSpace(fullDir) || string.IsNullOrEmpty(fullDir))//空代表根目录
{
return dirList.ToArray();
}
string currentDir = fullDir;
while (true)
{
dirList.Add(currentDir);
string parentDir = Path.GetDirectoryName(currentDir);
if ((string.IsNullOrWhiteSpace(parentDir) || string.IsNullOrEmpty(parentDir)))
{
break;
}
currentDir = Path.GetDirectoryName(currentDir);
}
dirList = dirList.OrderBy(i => i.Length).ToList();
return dirList.ToArray();
}
#endregion
/// <summary>
/// 下载
/// </summary>
public void Download(string destFilePath, string fileName)
{
try
{
string legaleName = this.getLegalName(fileName);
FileStream outputStream = new FileStream(destFilePath, FileMode.Create);
FtpWebRequest reqFTP;
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + legaleName));
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
reqFTP.UseBinary = true;
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
Stream ftpStream = response.GetResponseStream();
long cl = response.ContentLength;
int bufferSize = 2048;
int readCount;
byte[] buffer = new byte[bufferSize];
readCount = ftpStream.Read(buffer, 0, bufferSize);
while (readCount > 0)
{
outputStream.Write(buffer, 0, readCount);
readCount = ftpStream.Read(buffer, 0, bufferSize);
}
ftpStream.Close();
outputStream.Close();
response.Close();
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
/// <summary>
/// 删除文件
/// </summary>
public void Delete(string fileName)
{
try
{
string legaleName = this.getLegalName(fileName);
FtpWebRequest reqFTP;
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + legaleName));
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
reqFTP.Method = WebRequestMethods.Ftp.DeleteFile;
reqFTP.KeepAlive = false;
string result = String.Empty;
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
long size = response.ContentLength;
Stream datastream = response.GetResponseStream();
StreamReader sr = new StreamReader(datastream);
result = sr.ReadToEnd();
sr.Close();
datastream.Close();
response.Close();
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
/// <summary>
/// 删除文件
/// </summary>
public void RemoveDirectory(string dir)
{
try
{
string legaleName = this.getLegalName(dir);
FtpWebRequest reqFTP;
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + legaleName));
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
reqFTP.Method = WebRequestMethods.Ftp.RemoveDirectory;
reqFTP.KeepAlive = false;
string result = String.Empty;
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
long size = response.ContentLength;
Stream datastream = response.GetResponseStream();
StreamReader sr = new StreamReader(datastream);
result = sr.ReadToEnd();
sr.Close();
datastream.Close();
response.Close();
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
/// <summary>
/// 获取当前目录下明细(包含文件和文件夹)
/// </summary>
public string[] GetFilesDetailList(string destDir)
{
try
{
List<string> result = new List<string>();
string legaleName = this.getLegalName(destDir);
FtpWebRequest ftp;
ftp = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + legaleName));
ftp.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
ftp.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
WebResponse response = ftp.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
string line = reader.ReadLine();
while (line != null)
{
result.Add(line);
line = reader.ReadLine();
}
reader.Close();
response.Close();
return result.ToArray();
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
/// <summary>
/// 获取当前目录下文件列表(不包括文件夹)
/// <para>前置条件,目录存在</para>
/// </summary>
public string[] GetFileList(string url, bool enalbeSsl = false)
{
List<string> files = new List<string>();
string legaleName = this.getLegalName(url);
FtpWebRequest reqFTP;
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(this.ftpURI + legaleName));
reqFTP.UseBinary = true;
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
reqFTP.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
reqFTP.EnableSsl = enalbeSsl;
WebResponse response = reqFTP.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
string line = reader.ReadLine();
while (line != null)
{
if (line.IndexOf("<DIR>") == -1)
{
files.Add(Regex.Match(line, @"[\s]+([\d]+) (.+$)", RegexOptions.IgnoreCase).Groups[2].Value);
}
line = reader.ReadLine();
}
reader.Close();
response.Close();
return files.ToArray();
}
/// <summary>
/// 判断指定的文件是否存在
/// <para>前置条件:该目录的父目录存在</para>
/// </summary>
/// <param name="RemoteFileName">远程文件名</param>
public bool FileExist(string RemoteFileName, bool enalbeSsl = false)
{
string parentDir = Path.GetDirectoryName(RemoteFileName);
if (!this.DirExsit(parentDir,enalbeSsl))
{
return false;
}
string[] fileList = GetFileList(parentDir,enalbeSsl);
foreach (string str in fileList)
{
if (str.Trim() == Path.GetFileName(RemoteFileName.Trim()))
{
return true;
}
}
return false;
}
/// <summary>
/// 创建文件夹
/// </summary>
public void MakeDir(string dirName, bool enalbeSsl = false)
{
string legaleName = this.getLegalName(dirName);
FtpWebRequest reqFTP;
try
{
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + legaleName));
reqFTP.Method = WebRequestMethods.Ftp.MakeDirectory;
reqFTP.UseBinary = true;
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
reqFTP.EnableSsl = enalbeSsl;
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
Stream ftpStream = response.GetResponseStream();
ftpStream.Close();
response.Close();
}
catch (WebException ex)
{
throw ex;
}
}
/// <summary>
/// 获取指定文件大小
/// </summary>
/// <param name="filename"></param>
/// <returns>除以1024为KB,除以1024*1024为MB</returns>
public long GetFileSize(string filename, bool enalbeSsl = false)
{
FtpWebRequest reqFTP;
long fileSize = 0;
string legaleName = this.getLegalName(filename);
try
{
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + legaleName));
reqFTP.Method = WebRequestMethods.Ftp.GetFileSize;
reqFTP.UseBinary = true;
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
reqFTP.EnableSsl = enalbeSsl;
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
Stream ftpStream = response.GetResponseStream();
fileSize = response.ContentLength;
ftpStream.Close();
response.Close();
}
catch (Exception ex)
{
throw ex;
}
return fileSize;
}
#region private
private string getLegalName(string name)
{
return name.Replace("#", "%23").Replace("&", "%26").
Replace("=", "%3D").Replace("?", "%25")
.Replace("+", "%2B").Replace(" ", "%20").Replace("/", "%2F");
}
#endregion
}