C#操作FTP帮助类
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
namespace Common
{
///
/// FTP操作类
/// 20180403 周黎编写
///
public class FTPHelpers
{
///
/// FTP地址
///
private string _ftpServerIp;
///
/// FTP目录下准备操作文件夹名称
///
private string _ftpRemotePath;
///
/// FTP目录下准备操作文件夹名称
///
public string FtpRemotePath
{
get { return _ftpRemotePath; }
set
{
_ftpRemotePath = value;
if (!string.IsNullOrWhiteSpace(_ftpRemotePath))
this._ftpUri = "ftp://" + _ftpServerIp + "/" + _ftpRemotePath + "/";
else
this._ftpUri = "ftp://" + _ftpServerIp + "/";
}
}
///
/// FTP账号
///
private string _ftpUserId;
///
/// FTP密码
///
private string _ftpPassword;
private string _localSavePath;
///
/// FTP当前操作目录
///
private string _ftpUri;
///
/// 初始化参数
///
///
///
///
///
///
public void InitFtp(string ftpServerIp, string ftpRemotePath, string ftpUserId, string ftpPassword, string localSavePath)
{
this._ftpServerIp = ftpServerIp;
this._ftpUserId = ftpUserId;
this._ftpPassword = ftpPassword;
this._localSavePath = localSavePath;
FtpRemotePath = ftpRemotePath;
if (!string.IsNullOrWhiteSpace(this._localSavePath) && !Directory.Exists(this._localSavePath))
{
try
{
Directory.CreateDirectory(this._localSavePath);
}
catch { }
}
}
public void InitFtp(string ftpServerIp, string ftpUserId, string ftpPassword, string localSavePath)
{
InitFtp(ftpServerIp, "", ftpUserId, ftpPassword, localSavePath);
}
///
/// 上传
///
///
public void Upload(string filename)
{
FileInfo fileInf = new FileInfo(filename);
string uri = _ftpUri + fileInf.Name;
FtpWebRequest reqFTP;
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
reqFTP.Credentials = new NetworkCredential(_ftpUserId, _ftpPassword);
reqFTP.KeepAlive = false;
reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
reqFTP.UseBinary = true;
reqFTP.ContentLength = fileInf.Length;
int buffLength = 2048;
byte[] buff = new byte[buffLength];
int contentLen;
FileStream fs = null;
try
{
fs = fileInf.OpenRead();
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();
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (fs != null)
fs.Close();
}
}
public void Upload(byte[] buffer, string filename)
{
string uri = _ftpUri + filename;
FtpWebRequest reqFTP;
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
reqFTP.Credentials = new NetworkCredential(_ftpUserId, _ftpPassword);
reqFTP.KeepAlive = false;
reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
reqFTP.UseBinary = true;
reqFTP.ContentLength = buffer.Length;
try
{
Stream strm = reqFTP.GetRequestStream();
strm.Write(buffer, 0, buffer.Length);
strm.Close();
}
catch (Exception ex)
{
throw ex;
}
}
public void Upload(string ftpUri, string ftpUserId, string ftpPassword, string filename)
{
FileStream fs = null;
try
{
FileInfo fileInf = new FileInfo(filename);
string uri = ftpUri + fileInf.Name;
FtpWebRequest reqFTP;
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
reqFTP.Credentials = new NetworkCredential(ftpUserId, ftpPassword);
reqFTP.KeepAlive = false;
reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
reqFTP.UseBinary = true;
reqFTP.ContentLength = fileInf.Length;
int buffLength = 2048;
byte[] buff = new byte[buffLength];
int contentLen;
fs = fileInf.OpenRead();
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();
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (fs != null)
fs.Close();
}
}
///
/// 下载
///
///
///
public string Download(string fileName)
{
if (string.IsNullOrEmpty(fileName))
return null;
FtpWebRequest reqFTP;
FileStream outputStream = null;
FileStream fs = null;
string content = "";
try
{
outputStream = new FileStream(_localSavePath + "\\" + fileName, FileMode.Create);
reqFTP = (FtpWebRequest)WebRequest.Create(new Uri(_ftpUri + fileName));
reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
reqFTP.UseBinary = true;
reqFTP.Credentials = new NetworkCredential(_ftpUserId, _ftpPassword);
var response = (FtpWebResponse)reqFTP.GetResponse();
var ftpStream = response.GetResponseStream();
var cl = response.ContentLength;
var 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();
//Buffer.Log(string.Format("Ftp文件{1}下载成功!" , DateTime.Now.ToString(), fileName));
fs = new FileStream(_localSavePath + "\\" + fileName, FileMode.Open);
var sr = new StreamReader(fs);
content = sr.ReadToEnd();
sr.Close();
fs.Close();
Delete(fileName);
}
catch (Exception ex)
{
if (outputStream != null)
outputStream.Close();
if (fs != null)
fs.Close();
throw ex;
}
return content;
}
public byte[] DownloadByte(string fileName)
{
if (string.IsNullOrEmpty(fileName))
return null;
FtpWebRequest reqFTP;
byte[] buff = null;
try
{
reqFTP = (FtpWebRequest)WebRequest.Create(new Uri(_ftpUri + fileName));
reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
reqFTP.UseBinary = true;
reqFTP.Credentials = new NetworkCredential(_ftpUserId, _ftpPassword);
var response = (FtpWebResponse)reqFTP.GetResponse();
var ftpStream = response.GetResponseStream();
MemoryStream stmMemory = new MemoryStream();
byte[] buffer = new byte[64 * 1024];
int i;
while ((i = ftpStream.Read(buffer, 0, buffer.Length)) > 0)
{
stmMemory.Write(buffer, 0, i);
}
buff = stmMemory.ToArray();
stmMemory.Close();
ftpStream.Close();
response.Close();
}
catch (Exception ex)
{
throw ex;
}
return buff;
}
///
/// 删除文件(根据文件名进行删除需要指定操作路径)
///
///
public void Delete(string fileName)
{
try
{
string uri = _ftpUri + fileName;
FtpWebRequest reqFTP;
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
reqFTP.Credentials = new NetworkCredential(_ftpUserId, _ftpPassword);
reqFTP.KeepAlive = false;
reqFTP.Method = WebRequestMethods.Ftp.DeleteFile;
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();
//Buffer.Log(string.Format("Ftp文件{1}删除成功!", DateTime.Now.ToString(), fileName));
}
catch (Exception ex)
{
throw ex;
}
}
///
/// 删除文件夹(只针对空文件夹)
///
///
public void RemoveDirectory(string folderName)
{
try
{
string uri = _ftpUri + folderName;
FtpWebRequest reqFTP;
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
reqFTP.Credentials = new NetworkCredential(_ftpUserId, _ftpPassword);
reqFTP.KeepAlive = false;
reqFTP.Method = WebRequestMethods.Ftp.RemoveDirectory;
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 ex;
}
}
///
/// 删除文件夹以及其下面的所有内容
///
/// ftp
public void DeleteFtpDirWithAll(FTPHelpers ftp, bool isdelDqFile = true)
{
string[] fileList = ftp.GetFileList("");//获取所有文件列表(仅文件)
//1.首先删除所有的文件
if (fileList != null && fileList.Length > 0)
{
foreach (string file in fileList)
{
ftp.Delete(file);
}
}
//获取所有文件夹列表(仅文件夹)
string[] emptyDriList = ftp.GetDirectoryList();
foreach (string dir in emptyDriList)
{
//有时候会出现空的子目录,这时候要排除
if (string.IsNullOrWhiteSpace(dir))
{
continue;
}
string curDir = "/" + dir;
ftp.FtpRemotePath = ftp.FtpRemotePath + curDir;
//(判断当前目录下是否有文件,有则删除)
if (ftp.GetFileList("") != null && ftp.GetFileList("").Length > 0)
{
foreach (string file in ftp.GetFileList(""))
{
ftp.Delete(file);
}
}
//是否有子文件夹存在
if (ftp.GetDirectoryList() != null && ftp.GetDirectoryList().Length > 0)
{
DeleteFtpDirWithAll(ftp);//如果有就继续递归
}
ftp.FtpRemotePath = ftp.FtpRemotePath.Replace(curDir, "");//回退到上级目录以删除其本身
ftp.RemoveDirectory(dir);//删除当前文件夹
}
if (isdelDqFile && emptyDriList.Length > 0)
ftp.RemoveDirectory("");
}
///
/// 获取当前目录下明细(包含文件和文件夹)
///
///
public string[] GetFilesDetailList()
{
//string[] downloadFiles;
try
{
StringBuilder result = new StringBuilder();
FtpWebRequest ftp;
ftp = (FtpWebRequest)FtpWebRequest.Create(new Uri(_ftpUri));
ftp.Credentials = new NetworkCredential(_ftpUserId, _ftpPassword);
ftp.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
WebResponse response = ftp.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
//while (reader.Read() > 0)
//{
//}
string line = reader.ReadLine();
//line = reader.ReadLine();
//line = reader.ReadLine();
while (line != null)
{
result.Append(line);
result.Append("\n");
line = reader.ReadLine();
}
if (result.Length == 0)
return null;
result.Remove(result.ToString().LastIndexOf("\n"), 1);
reader.Close();
response.Close();
return result.ToString().Split('\n');
}
catch (Exception ex)
{
return null;
}
}
///
/// 获取当前目录下文件列表(仅文件)
///
///
///
public string[] GetFileList(string mask)
{
string[] downloadFiles = null;
StringBuilder result = new StringBuilder();
FtpWebRequest reqFTP;
try
{
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(_ftpUri));
reqFTP.UseBinary = true;
reqFTP.Credentials = new NetworkCredential(_ftpUserId, _ftpPassword);
reqFTP.Method = WebRequestMethods.Ftp.ListDirectory;
WebResponse response = reqFTP.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
string line = reader.ReadLine();
while (line != null)
{
if (mask.Trim() != string.Empty && mask.Trim() != "*.*")
{
string mask_ = mask.Substring(0, mask.IndexOf("*"));
if (line.Substring(0, mask_.Length) == mask_)
{
result.Append(line);
result.Append("\n");
}
}
else
{
result.Append(line);
result.Append("\n");
}
line = reader.ReadLine();
}
if (result.Length == 0)
return new string[] { };
result.Remove(result.ToString().LastIndexOf('\n'), 1);
reader.Close();
response.Close();
downloadFiles = result.ToString().Split('\n');
//ArrayList list = new ArrayList(downloadFiles);
//list.RemoveAt(downloadFiles.Length - 1);
//downloadFiles= list.ToArray(typeof(string)) as string[];
}
catch (Exception ex)
{
return new string[] { };
}
if (downloadFiles == null)
downloadFiles = new string[] { };
return downloadFiles;
}
public string GetSingleFile()
{
var list = GetFileList("*.*");
if (list != null && list.Length > 0)
return list[0];
else
return null;
}
///
/// 获取当前目录下所有的文件夹列表(仅文件夹)
///
///
public string[] GetDirectoryList()
{
string[] drectory = GetFilesDetailList();
if (drectory == null)
return new string[] { };
string m = string.Empty;
foreach (string str in drectory)
{
int dirPos = str.IndexOf("
");
if (dirPos > 0)
{
/*判断 Windows 风格*/
m += str.Substring(dirPos + 5).Trim() + "\n";
}
else if (str.Trim().Substring(0, 1).ToUpper() == "D")
{
/*判断 Unix 风格*/
string dir = str.Substring(54).Trim();
if (dir != "." && dir != "..")
{
m += dir + "\n";
}
}
}
char[] n = new char[] { '\n' };
ArrayList list = new ArrayList(m.Split(n));
list.RemoveAt(m.Split(n).Length - 1);
return list.ToArray(typeof(string)) as string[];
}
///
/// 判断当前目录下指定的子目录是否存在
///
/// 指定的目录名
public bool DirectoryExist(string RemoteDirectoryName)
{
string[] dirList = GetDirectoryList();
if (dirList != null)
{
foreach (string str in dirList)
{
if (str.Trim() == RemoteDirectoryName.Trim())
{
return true;
}
}
}
return false;
}
///
/// 判断当前目录下指定的文件是否存在
///
/// 远程文件名
public bool FileExist(string RemoteFileName)
{
string[] fileList = GetFileList("*.*");
foreach (string str in fileList)
{
if (str.Trim() == RemoteFileName.Trim())
{
return true;
}
}
return false;
}
///
/// 创建文件夹
///
///
public void MakeDir(string dirName)
{
FtpWebRequest reqFTP;
try
{
// dirName = name of the directory to create.
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(_ftpUri + dirName));
reqFTP.Method = WebRequestMethods.Ftp.MakeDirectory;
reqFTP.UseBinary = true;
reqFTP.Credentials = new NetworkCredential(_ftpUserId, _ftpPassword);
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
Stream ftpStream = response.GetResponseStream();
ftpStream.Close();
response.Close();
}
catch (Exception ex)
{
throw ex;
}
}
///
/// 获取指定文件大小
///
///
///
public long GetFileSize(string filename)
{
FtpWebRequest reqFTP;
long fileSize = 0;
try
{
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(_ftpUri + filename));
reqFTP.Method = WebRequestMethods.Ftp.GetFileSize;
reqFTP.UseBinary = true;
reqFTP.Credentials = new NetworkCredential(_ftpUserId, _ftpPassword);
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
Stream ftpStream = response.GetResponseStream();
fileSize = response.ContentLength;
ftpStream.Close();
response.Close();
}
catch (Exception ex)
{
//throw new Exception("FtpWeb:GetFileSize Error --> " + ex.Message);
}
return fileSize;
}
///
/// 改名
///
///
///
public void ReName(string currentFilename, string newFilename)
{
FtpWebRequest reqFTP;
try
{
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(_ftpUri + currentFilename));
reqFTP.Method = WebRequestMethods.Ftp.Rename;
reqFTP.RenameTo = newFilename;
reqFTP.UseBinary = true;
reqFTP.Credentials = new NetworkCredential(_ftpUserId, _ftpPassword);
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
Stream ftpStream = response.GetResponseStream();
ftpStream.Close();
response.Close();
}
catch (Exception ex)
{
throw ex;
}
}
///
/// 移动文件
///
///
///
public void MovieFile(string currentFilename, string newDirectory)
{
ReName(currentFilename, newDirectory);
}
}
}
评论
隐私政策
你无需删除空行,直接评论以获取最佳展示效果