string ftpUserID;//用户名
string ftpPassword;//密码
FtpWebRequest reqFTP;
#region 连接服务器
/// <summary>
/// 连接服务器
/// </summary>
/// <param name="path"></param>
private void Connect(String path)
{
// 根据uri创建FtpWebRequest对象
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(path));
// 指定数据传输类型
reqFTP.UseBinary = true;
// ftp用户名和密码
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
reqFTP.KeepAlive = false;
}
#endregion
#region 获得文件列表
/// <summary>
/// 获得文件列表
/// </summary>
/// <param name="path"></param>
/// <param name="WRMethods"></param>
/// <returns></returns>
private string[] GetFileList(string path, string WRMethods)
{
string[] downloadFiles;
WebResponse response = null;
StreamReader reader = null;
StringBuilder result = new StringBuilder();
try
{
Connect(path);
reqFTP.Method = WRMethods;
response = reqFTP.GetResponse();
reader = new StreamReader(response.GetResponseStream(), Encoding.Default);//中文文件名
string line = reader.ReadLine();
while (line != null)
{
result.Append(line);
result.Append("\n");
line = reader.ReadLine();
}
// to remove the trailing '\n'
result.Remove(result.ToString().LastIndexOf('\n'), 1);
return result.ToString().Split('\n');
}
catch (Exception ex)
{
//System.Windows.Forms.MessageBox.Show(ex.Message);
RetMsg = ex.Message;
downloadFiles = null;
return downloadFiles;
}
finally
{
if (reader != null)
{
reader.Close();
}
if (response != null)
{
response.Close();
}
}
}
/// <summary>
/// 获得文件列表
/// </summary>
/// <param name="ftpSubdir"></param>
/// <returns></returns>
public string[] GetFileList(string ftpSubdir)
{
return GetFileList("ftp://" + ftpServerIP + "/" + ftpSubdir, WebRequestMethods.Ftp.ListDirectory);
}
/// <summary>
/// 获得文件列表
/// </summary>
/// <returns></returns>
public string[] GetFileList()
{
return GetFileList("");
}
/// <summary>
/// 获得文件列表明细
/// </summary>
/// <param name="ftpSubdir"></param>
/// <returns></returns>
public string[] GetFilesDetailList(string ftpSubdir)
{
return GetFileList("ftp://" + ftpServerIP + "/" + ftpSubdir, WebRequestMethods.Ftp.ListDirectoryDetails);
}
/// <summary>
/// 获得文件列表明细
/// </summary>
/// <returns></returns>
public string[] GetFilesDetailList()
{
return GetFilesDetailList("");
}
#endregion
#region 文件上传下载
/// <summary>
/// 文件上传
/// </summary>
/// <param name="filename"></param>
/// <param name="ftpSubdir"></param>
/// <returns></returns>
public bool Upload(string filename, string ftpSubdir)
{
FileStream fs = null;
Stream strm = null;
try
{
FileInfo fileInf = new FileInfo(filename);
string uri = "ftp://" + ftpServerIP + "/" + ftpSubdir + fileInf.Name;
Connect(uri);//连接
// 默认为true,连接不会被关闭
// 在一个命令之后被执行
reqFTP.KeepAlive = false;
// 指定执行什么命令
reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
// 上传文件时通知服务器文件的大小
reqFTP.ContentLength = fileInf.Length;
// 缓冲大小设置为kb
int buffLength = 2048;
byte[] buff = new byte[buffLength];
int contentLen;
// 打开一个文件流(System.IO.FileStream) 去读上传的文件
fs = fileInf.OpenRead();
// 把上传的文件写入流
strm = reqFTP.GetRequestStream();
// 每次读文件流的kb
contentLen = fs.Read(buff, 0, buffLength);
// 流内容没有结束
while (contentLen != 0)
{
// 把内容从file stream 写入upload stream
strm.Write(buff, 0, contentLen);
contentLen = fs.Read(buff, 0, buffLength);
}
return true;
}
catch (Exception ex)
{
//SystemMessge.Warning(ex.Message, "上传出错");
RetMsg = ex.Message;
return false;
}
finally
{
// 关闭两个流
if (strm != null)
{
strm.Close();
}
if (fs != null)
{
fs.Close();
}
}
}
/// <summary>
/// 文件上传
/// </summary>
/// <param name="filename"></param>
/// <returns></returns>
public bool Upload(string filename)
{
return Upload(filename, "");
}
/// <summary>
/// 文件下载
/// </summary>
/// <param name="filePath"></param>
/// <param name="fileName"></param>
/// <param name="ftpSubdir"></param>
/// <returns></returns>
public bool Download(string filePath, string fileName, string ftpSubdir)
{
log.Info(string.Format("进入Download文件下载功能,路径:{0},文件名:{1} ", filePath, fileName));
FtpWebResponse response = null;
Stream ftpStream = null;
FileStream outputStream = null;
try
{
String onlyFileName = Path.GetFileName(fileName);
string newFileName = filePath + "\\" + onlyFileName;
log.Info(string.Format("本地文件路径:{0} ", newFileName));
if (File.Exists(newFileName))
{
log.Info("本地已存在该文件,先删除本地文件");
File.Delete(newFileName);
}
string url = "ftp://" + ftpServerIP + "/" + ftpSubdir + fileName;
log.Info(string.Format("FTPUrl:{0} ", url));
Connect(url);//连接
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
response = (FtpWebResponse)reqFTP.GetResponse();
ftpStream = response.GetResponseStream();
long cl = response.ContentLength;
int bufferSize = 2048;
int readCount;
byte[] buffer = new byte[bufferSize];
readCount = ftpStream.Read(buffer, 0, bufferSize);
outputStream = new FileStream(newFileName, FileMode.Create);
while (readCount > 0)
{
log.Info("下载文件写入本地");
outputStream.Write(buffer, 0, readCount);
readCount = ftpStream.Read(buffer, 0, bufferSize);
}
log.Info("文件下载成功!");
return true;
}
catch (Exception ex)
{
log.Info(string.Format("文件下载失败,失败原因:{0} ", ex.Message));
RetMsg = ex.Message;
return false;
}
finally
{
if (ftpStream != null)
{
ftpStream.Close();
}
if (outputStream != null)
{
outputStream.Close();
}
if (response != null)
{
response.Close();
}
}
}
/// <summary>
/// 文件下载
/// </summary>
/// <param name="filePath"></param>
/// <param name="fileName"></param>
/// <returns></returns>
public bool Download(string filePath, string fileName)
{
return Download(filePath, fileName, "");
}
#endregion
/// <summary>
/// 文件下载
/// </summary>
/// <param name="filePath"></param>
/// <param name="fileName"></param>
/// <param name="ftpSubdir"></param>
/// <returns></returns>
public bool Download(string filePath, string fileName, string ftpSubdir)
{
log.Info(string.Format("进入Download文件下载功能,路径:{0},文件名:{1} ", filePath, fileName));
FtpWebResponse response = null;
Stream ftpStream = null;
FileStream outputStream = null;
try
{
String onlyFileName = Path.GetFileName(fileName);
string newFileName = filePath + "\\" + onlyFileName;
log.Info(string.Format("本地文件路径:{0} ", newFileName));
if (File.Exists(newFileName))
{
log.Info("本地已存在该文件,先删除本地文件");
File.Delete(newFileName);
}
string url = "ftp://" + ftpServerIP + "/" + ftpSubdir + fileName;
log.Info(string.Format("FTPUrl:{0} ", url));
Connect(url);//连接
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
response = (FtpWebResponse)reqFTP.GetResponse();
ftpStream = response.GetResponseStream();
long cl = response.ContentLength;
int bufferSize = 2048;
int readCount;
byte[] buffer = new byte[bufferSize];
readCount = ftpStream.Read(buffer, 0, bufferSize);
outputStream = new FileStream(newFileName, FileMode.Create);
while (readCount > 0)
{
log.Info("下载文件写入本地");
outputStream.Write(buffer, 0, readCount);
readCount = ftpStream.Read(buffer, 0, bufferSize);
}
log.Info("文件下载成功!");
return true;
}
catch (Exception ex)
{
log.Info(string.Format("文件下载失败,失败原因:{0} ", ex.Message));
RetMsg = ex.Message;
return false;
}
finally
{
if (ftpStream != null)
{
ftpStream.Close();
}
if (outputStream != null)
{
outputStream.Close();
}
if (response != null)
{
response.Close();
}
}
}
/// <summary>
/// 判断文件是否存在
/// </summary>
/// <param name="fileName"></param>
/// <param name="ftpSubdir"></param>
/// <returns></returns>
public bool FileExists(string fileName, string ftpSubdir)
{
bool success = false;
StreamReader reader = null;
WebResponse response = null;
try
{
Connect("ftp://" + ftpServerIP + "/" + ftpSubdir);
reqFTP.Method = WebRequestMethods.Ftp.ListDirectory;
response = reqFTP.GetResponse();
reader = new StreamReader(response.GetResponseStream(), Encoding.Default);//中文文件名
string line = reader.ReadLine();
while (line != null)
{
if (line == fileName)
{
success = true;
break;
}
line = reader.ReadLine();
}
return success;
}
catch (Exception ex)
{
//System.Windows.Forms.MessageBox.Show(ex.Message);
RetMsg = ex.Message;
return false;
}
finally
{
if (reader != null)
{
reader.Close();
}
if (response != null)
{
response.Close();
}
}
}
/// <summary>
/// 删除文件
/// </summary>
/// <param name="fileName"></param>
/// <param name="ftpSubdir"></param>
public bool DeleteFileName(string fileName, string ftpSubdir)
{
FtpWebResponse response = null;
try
{
FileInfo fileInf = new FileInfo(fileName);
string uri = "ftp://" + ftpServerIP + "/" + ftpSubdir + fileInf.Name;
Connect(uri);//连接
// 默认为true,连接不会被关闭
// 在一个命令之后被执行
reqFTP.KeepAlive = false;
// 指定执行什么命令
reqFTP.Method = WebRequestMethods.Ftp.DeleteFile;
response = (FtpWebResponse)reqFTP.GetResponse();
return true;
}
catch (Exception ex)
{
//SystemMessge.Warning(ex.Message, "删除错误");
RetMsg = ex.Message;
return false;
}
finally
{
if (response != null)
{
response.Close();
}
}
}
/// <summary>
/// 创建目录
/// </summary>
/// <param name="dirName"></param>
/// <param name="ftpSubdir"></param>
/// <returns></returns>
public bool MakeDir(string dirName, string ftpSubdir)
{
FtpWebResponse response = null;
try
{
string uri = "ftp://" + ftpServerIP + "/" + ftpSubdir + dirName;
Connect(uri);//连接
reqFTP.Method = WebRequestMethods.Ftp.MakeDirectory;
response = (FtpWebResponse)reqFTP.GetResponse();
return true;
}
catch (Exception ex)
{
//SystemMessge.Warning(ex.Message);
RetMsg = ex.Message;
return false;
}
finally
{
if (response != null)
{
response.Close();
}
}
}
/// <summary>
/// 删除目录
/// </summary>
/// <param name="DirName"></param>
/// <returns></returns>
public bool DeleteDir(string DirName)
{
FtpWebResponse response = null;
try
{
string uri = "ftp://" + ftpServerIP + "/" + DirName;
Connect(uri);//连接
reqFTP.Method = WebRequestMethods.Ftp.RemoveDirectory;
response = (FtpWebResponse)reqFTP.GetResponse();
return true;
}
catch (Exception ex)
{
//SystemMessge.Warning(ex.Message);
RetMsg = ex.Message;
return false;
}
finally
{
if (response != null)
{
response.Close();
}
}
}
/// <summary>
/// 获得文件大小
/// </summary>
/// <param name="filename"></param>
/// <param name="ftpSubdir"></param>
/// <returns></returns>
public long GetFileSize(string filename, string ftpSubdir)
{
long fileSize = 0;
FtpWebResponse response = null;
try
{
FileInfo fileInf = new FileInfo(filename);
string uri = "ftp://" + ftpServerIP + "/" + ftpSubdir + fileInf.Name;
Connect(uri);//连接
reqFTP.Method = WebRequestMethods.Ftp.GetFileSize;
response = (FtpWebResponse)reqFTP.GetResponse();
fileSize = response.ContentLength;
return fileSize;
}
catch (Exception ex)
{
//SystemMessge.Warning(ex.Message);
RetMsg = ex.Message;
return 0;
}
finally
{
if (response != null)
{
response.Close();
}
}
}
/// <summary>
/// 文件改名
/// </summary>
/// <param name="currentFilename"></param>
/// <param name="newFilename"></param>
/// <param name="ftpSubdir"></param>
/// <returns></returns>
public bool Rename(string currentFilename, string newFilename, string ftpSubdir)
{
FtpWebResponse response = null;
try
{
FileInfo fileInf = new FileInfo(currentFilename);
string uri = "ftp://" + ftpServerIP + "/" + ftpSubdir + fileInf.Name;
Connect(uri);//连接
reqFTP.Method = WebRequestMethods.Ftp.Rename;
reqFTP.RenameTo = newFilename;
response = (FtpWebResponse)reqFTP.GetResponse();
return true;
}
catch (Exception ex)
{
//SystemMessge.Warning(ex.Message);
RetMsg = ex.Message;
return false;
}
finally
{
if (response != null)
{
response.Close();
}
}
}