using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net;
using System.IO;
using System.Text;
namespace TecoWebService.Utility
{
/// <summary>
/// 文件夹下的内容项信息
/// </summary>
public class DirItemInfo
{
/// <summary>
/// 文件所在目录,(父目录)
/// </summary>
public string ParentFolder { set; get; }
/// <summary>
/// 文件类型 0:是文件,1是文件夹
/// </summary>
public int FileType { set; get; }
/// <summary>
/// 文件名
/// </summary>
public string Name { set; get; }
/// <summary>
/// 文件全路径
/// </summary>
public string FullFileName { set; get; }
}
public class FtpUtil
{
private string ftpUserName;
private string ftpPassword;
/// <summary>
/// 连接服务器
/// </summary>
/// <param name="server">服务器地址(IP)</param>
/// <param name="userName">登录名</param>
/// <param name="pwd">密码</param>
/// <returns></returns>
public void InitFtpParam(string userName, string pwd)
{
ftpUserName = userName;
ftpPassword = pwd;
}
/// <summary>
/// 上传本地文件夹到ftp
/// </summary>
/// <param name="localDir">本地文件目录</param>
/// <param name="ftpPath">目标ftp目录</param>
/// <param name="dirName">文件夹名称</param>
public string UploadDirectory(string localDir, string ftpPath, string dirName)
{
localDir = FolderFormat(localDir, '\\');
ftpPath = FolderFormat(ftpPath, '/');
string dir = localDir + dirName + @"\"; //获取当前目录(父目录在目录名)
if (!Directory.Exists(dir))
{
return dir + "目录不存在";
}
if (DirExist(ftpPath, dirName))
{
// 删除指定目录
DeleteDir(ftpPath, dirName);
}
// 创建文件夹
MakeDir(ftpPath, dirName);
List<List<string>> infos = GetLocalDirDetails(dir); //获取当前目录下的所有文件和文件夹
//先上传文件
for (int i = 0; i < infos[0].Count; i++)
{
Console.WriteLine(infos[0][i]);
UploadFile(dir + infos[0][i], ftpPath + dirName + @"/" + infos[0][i]);
}
//再处理文件夹
for (int i = 0; i < infos[1].Count; i++)
{
UploadDirectory(dir, ftpPath + dirName + @"/", infos[1][i]);
}
return "0";
}
/// <summary>
/// 上传文件到ftp
/// </summary>
/// <param name="localFile"></param>
/// <param name="ftpPath"></param>
/// <returns></returns>
public bool UploadFile(string localFile, string ftpFile)
{
if (!File.Exists(localFile))
{
return false;
}
using (FileStream fs = new FileInfo(localFile).OpenRead())
{
byte[] fileBuff = new byte[fs.Length];
fs.Read(fileBuff, 0, Convert.ToInt32(fs.Length));
return UploadFile(fileBuff, localFile.Length ,ftpFile);
}
}
/// <summary>
/// 上传文件
/// </summary>
/// <param name="fs">文件流</param>
/// <param name="ftpFile">ftp文件地址</param>
/// <returns></returns>
public bool UploadFile(byte[] fileBuff, int fileNameLen, string ftpFile)
{
try
{
FtpWebRequest ftpWebRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpFile));
ftpWebRequest.Credentials = new NetworkCredential(ftpUserName, ftpPassword);
ftpWebRequest.UseBinary = true;
ftpWebRequest.UsePassive = true;
ftpWebRequest.KeepAlive = false;
ftpWebRequest.Method = WebRequestMethods.Ftp.UploadFile;
ftpWebRequest.ContentLength = fileNameLen;
//int buffLength = 2048;
//int curIndex = 0;
using (Stream rs = ftpWebRequest.GetRequestStream())
{
rs.Write(fileBuff, 0, fileBuff.Length);
rs.Close();
}
return true;
}
catch (Exception ex) { }
return false;
}
/// <summary>
/// 从ftp下载文件目录
/// </summary>
/// <param name="ftpPath">ftp文件夹所在父目录</param>
/// <param name="localDir">要下载到的本地文件目录</param>
/// <param name="dirName">文件夹名称</param>
/// <returns></returns>
public bool DownloadDirectory(string ftpPath, string localDir, string dirName)
{
try
{
// ftp 目录
string ftpDir = FolderFormat(ftpPath, '/') + dirName;
// 本地目录
string downloadDir = FolderFormat(localDir, '\\') + dirName;
// 获得文件夹下所有内容
if (!Directory.Exists(downloadDir))
{
Directory.CreateDirectory(downloadDir);
}
// 获得ftp文件夹内容
List<DirItemInfo> ftpFileInfos = GetFtpFileInfos(ftpDir);
for (int i = 0; i < ftpFileInfos.Count; ++i)
{
DirItemInfo ftpFileInfo = ftpFileInfos[i];
if (ftpFileInfos[i].FileType == 0) // 文件夹
{
DownloadDirectory(ftpDir, downloadDir, ftpFileInfos[i].Name);
}
else if (ftpFileInfos[i].FileType == 1) // 文件
{
DownloadFile(ftpDir, downloadDir, ftpFileInfos[i].Name);
}
}
return true;
}
catch (System.Exception ex)
{
}
return false;
}
/// <summary>
/// 下载文件
/// </summary>
/// <param name="ftpDir">ftp文件目录</param>
/// <param name="fileName">文件名</param>
/// <returns>文件buffer</returns>
public byte[] DownloadFile(string ftpDir, string fileName)
{
FtpWebRequest reqFTP;
try
{
// 如果文件存在,则覆盖,否则创建文件
string ftpFileName = FolderFormat(ftpDir, '/') + fileName;
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpFileName));
reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
reqFTP.UseBinary = true;
reqFTP.Credentials = new NetworkCredential(ftpUserName, ftpPassword);
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
//StreamReader ftpFileListReader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
Stream ftpStream = response.GetResponseStream();
int len = 0;
List<byte> bytes = new List<byte>();
int ret = -1;
while ((ret = ftpStream.ReadByte()) != -1)
{
bytes.Add(Convert.ToByte(ret));
len++;
}
ftpStream.Close();
response.Close();
//byte[] filebuffer = ftpStream.ToArray();
// long fileLen = ftpFileListReader.
byte[] filebuffer = bytes.ToArray();
//ftpStream.Read(filebuffer, 0, Convert.ToInt32(len));
return filebuffer;
}
catch (Exception ex)
{
//throw ex.Message();
return null;
}
}
/// <summary>
/// 下载文件
/// </summary>
/// <param name="ftpDir"></param>
/// <param name="localDir"></param>
/// <param name="fileName"></param>
/// <returns></returns>
public bool DownloadFile(string ftpDir, string localDir, string fileName)
{
try
{
// 获得文件buffer
byte [] fileBuffer = DownloadFile(ftpDir, fileName);
if (fileBuffer.Length > 0)
{
// 如果文件存在,则覆盖,否则创建文件
FileStream outputStream = new FileStream(FolderFormat(localDir, '\\') + fileName, FileMode.Create);
int bufferSize = 2048; // 每次读2k
int readCount = bufferSize;
while (readCount <= fileBuffer.Length)
{
outputStream.Write(fileBuffer, 0, readCount);
readCount += bufferSize;
}
outputStream.Close();
}
return true;
}
catch (Exception ex)
{
//throw ex.Message();
return false;
}
}
/// <summary>
/// 获得文件夹下文件信息列表
/// </summary>
/// <param name="ftpPath">ftp文件目录</param>
/// <returns>目录下文件信息列表</returns>
public List<DirItemInfo> GetFtpFileInfos(string ftpPath)
{
try
{
List<DirItemInfo> fileInfos = new List<DirItemInfo>();
FtpWebRequest ftpRequest = (FtpWebRequest)WebRequest.Create(new Uri(ftpPath));
ftpRequest.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
ftpRequest.Credentials = new NetworkCredential(ftpUserName, ftpPassword);
WebResponse webresp = ftpRequest.GetResponse();
StreamReader ftpFileListReader = new StreamReader(webresp.GetResponseStream(), Encoding.UTF8);
StringBuilder result = new StringBuilder();
string line = ftpFileListReader.ReadLine();
while (line != null)
{
DirItemInfo fileInfo = new DirItemInfo();
string[] items = line.Split(' ');
if (items.Length > 0)
{
fileInfo.Name = items[items.Length - 1].Trim(); // 文件名
if (items[0].StartsWith("d"))
{
fileInfo.FileType = 0; // 文件夹
}
else
{
fileInfo.FileType = 1; // 文件
}
fileInfo.ParentFolder = FolderFormat(ftpPath, '/'); // 文件所在目录
fileInfo.FullFileName = fileInfo.ParentFolder + fileInfo.Name; // 文件全路径
fileInfos.Add(fileInfo);
}
line = ftpFileListReader.ReadLine();
}
ftpFileListReader.Close();
webresp.Close();
return fileInfos;
}
catch (Exception ex)
{
ex.ToString();
}
return null;
}
/// <summary>
/// 获得ftp文件列表
/// </summary>
/// <param name="ftpPath"></param>
/// <param name="type"></param>
/// <returns></returns>
public List<string> GetFtpFileList(string ftpPath, string type)
{
try
{
List<string> fileInfiList = new List<string>();
FtpWebRequest ftpRequest = (FtpWebRequest)WebRequest.Create(new Uri(ftpPath));
ftpRequest.Method = type;
ftpRequest.Credentials = new NetworkCredential(ftpUserName, ftpPassword);
WebResponse webresp = ftpRequest.GetResponse();
StreamReader ftpFileListReader = new StreamReader(webresp.GetResponseStream(), Encoding.UTF8);
StringBuilder result = new StringBuilder();
string line = ftpFileListReader.ReadLine();
while (line != null)
{
fileInfiList.Add(line);
line = ftpFileListReader.ReadLine();
}
ftpFileListReader.Close();
webresp.Close();
return fileInfiList;
}
catch(Exception ex)
{
ex.ToString();
}
return null;
}
/// <summary>
/// 在ftp指定目录下创建文件夹
/// </summary>
/// <param name="ftpPath">ftp目录</param>
/// <param name="dirName">要创建文件夹的名称</param>
/// <returns></returns>
public bool MakeDir(string ftpPath, string dirName)
{
try
{
//实例化FTP连接
FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(new Uri(FolderFormat(ftpPath, '/') + dirName));
request.Credentials = new NetworkCredential(ftpUserName, ftpPassword);
//指定FTP操作类型为创建目录
request.Method = WebRequestMethods.Ftp.MakeDirectory;
//获取FTP服务器的响应
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
response.Close();
return true;
}
catch (Exception ex)
{
}
return false;
}
/// <summary>
/// 判断ftp目录下是否存在某一文件夹
/// </summary>
/// <param name="ftpPath"></param>
/// <param name="dirName"></param>
/// <returns></returns>
public bool DirExist(string ftpPath, string dirName)
{
bool result = false;
try
{
//实例化FTP连接
FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpPath));
request.Credentials = new NetworkCredential(ftpUserName, ftpPassword);
//指定FTP操作类型为创建目录
request.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
//获取FTP服务器的响应
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.Default);
StringBuilder str = new StringBuilder();
string line = sr.ReadLine();
while (line != null)
{
str.Append(line);
str.Append("|");
line = sr.ReadLine();
}
string[] datas = str.ToString().Split('|');
for (int i = 0; i < datas.Length; i++)
{
if (datas[i].StartsWith("d"))
{
// 获得文件名
string[] items = datas[i].Split(' ');
if (items.Length > 0)
{
string name = items[items.Length - 1].Trim();
if (name == dirName)
{
result = true;
break;
}
}
}
}
sr.Close();
sr.Dispose();
response.Close();
}
catch (Exception ex)
{
}
return result;
}
public bool DeleteDir(string ftpPath, string folderName)
{
string curFolder = FolderFormat(ftpPath, '/') + folderName;
List<DirItemInfo> ftpFileInfos = GetFtpFileInfos(curFolder);
for (int i = 0; i < ftpFileInfos.Count; ++i)
{
DirItemInfo ftpFileInfo = ftpFileInfos[i];
if (ftpFileInfo.FileType == 0) // 删除文件夹
{
DeleteDir(curFolder, ftpFileInfo.Name);
}
else if (ftpFileInfo.FileType == 1)
{
DeleteFile(curFolder, ftpFileInfo.Name); // 删除文件
}
}
DeleteFolder(ftpPath, folderName);
return true;
}
/// <summary>
/// 删除指定位置的文件
/// </summary>
/// <param name="ftpPath">文件所在目录</param>
/// <param name="fileName">文件名</param>
/// <returns></returns>
public string DeleteFile(string ftpPath, string fileName)
{
FtpWebRequest reqFTP;
try
{
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(FolderFormat(ftpPath, '/') + fileName));
reqFTP.UseBinary = true;
reqFTP.UsePassive = false;
reqFTP.KeepAlive = false;
reqFTP.Credentials = new NetworkCredential(ftpUserName, ftpPassword);
reqFTP.Method = WebRequestMethods.Ftp.DeleteFile;
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
response.Close();
return "0";
}
catch (Exception ex)
{
return ex.ToString();
}
}
/// <summary>
/// 删除指定目录下的文件夹(如果该文件夹下存在文件夹则删除失败)
/// </summary>
/// <param name="ftpPath">ftp 目录</param>
/// <param name="dirName">文件夹名称</param>
/// <returns></returns>
private string DeleteFolder(string ftpPath, string dirName)
{
FtpWebRequest reqFTP;
try
{
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(FolderFormat(ftpPath, '/') + dirName));
reqFTP.UseBinary = true;
reqFTP.UsePassive = false;
reqFTP.KeepAlive = false;
reqFTP.Credentials = new NetworkCredential(ftpUserName, ftpPassword);
reqFTP.Method = WebRequestMethods.Ftp.RemoveDirectory;
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
response.Close();
return "0";
}
catch (Exception ex)
{
return ex.ToString();
}
}
/// <summary>
/// 格式化目录
/// </summary>
/// <param name="folderPath">要格式化的目录</param>
/// <param name="fromatChar">格式化的目录分隔符一般为 \ / </param>
/// <returns>格式化后的目录带目录分隔符</returns>
public static string FolderFormat(string folderPath, char fromatChar)
{
int pos = -1;
pos = folderPath.LastIndexOf(fromatChar);
if (pos != folderPath.Length - 1)
{
folderPath += fromatChar;
}
return folderPath;
}
/// <summary>
/// 获得当前目录的文件夹结构
/// </summary>
/// <param name="localDir"></param>
/// <returns></returns>
private List<List<string>> GetLocalDirDetails(string localDir)
{
List<List<string>> infos = new List<List<string>>();
try
{
infos.Add(Directory.GetFiles(localDir).ToList()); //获取当前目录的文件
infos.Add(Directory.GetDirectories(localDir).ToList()); //获取当前目录的目录
for (int i = 0; i < infos[0].Count; i++)
{
int index = infos[0][i].LastIndexOf(@"\");
infos[0][i] = infos[0][i].Substring(index + 1);
}
for (int i = 0; i < infos[1].Count; i++)
{
int index = infos[1][i].LastIndexOf(@"\");
infos[1][i] = infos[1][i].Substring(index + 1);
}
}
catch (Exception ex)
{
ex.ToString();
}
return infos;
}
}
}