|
参考一:
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Net;
using System.Globalization;
namespace FtpTest1
{
public class FtpWeb
{
string ftpServerIP;
string ftpRemotePath;
string ftpUserID;
string ftpPassword;
string ftpURI;
///
/// 连接FTP
///
/// FTP连接地址
/// 指定FTP连接成功后的当前目录, 如果不指定即默认为根目录
/// 用户名
/// 密码
public FtpWeb(string FtpServerIP, string FtpRemotePath, string FtpUserID, string FtpPassword)
{
ftpServerIP = FtpServerIP;
ftpRemotePath = FtpRemotePath;
ftpUserID = FtpUserID;
ftpPassword = FtpPassword;
ftpURI = "ftp://" + ftpServerIP + "/" ;
}
static void Main() {
//string file = "c:\\aq3.gifa";
//FileInfo fileInf = new FileInfo(file);
//if (!fileInf.Exists)
//{
// Console.WriteLine(file + " no exists");
//}
//else {
// Console.WriteLine("yes");
//}
//Console.ReadLine();
FtpWeb fw = new FtpWeb("121.11.65.10", "", "aa1", "aa");
string[] filePaths = { "c:\\aq3.gif1", "c:\\aq2.gif1", "c:\\bsmain_runtime.log" };
Console.WriteLine(fw.UploadFile(filePaths));
Console.ReadLine();
}
//上传文件
public string UploadFile( string[] filePaths ) {
StringBuilder sb = new StringBuilder();
if ( filePaths != null && filePaths.Length > 0 ){
foreach( var file in filePaths ){
sb.Append(Upload( file ));
}
}
return sb.ToString();
}
///
/// 上传文件
///
///
private string Upload(string filename)
{
FileInfo fileInf = new FileInfo(filename);
if ( !fileInf.Exists ){
return filename + " 不存在!\n";
}
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.UsePassive = false; //选择主动还是被动模式
//Entering Passive Mode
reqFTP.ContentLength = fileInf.Length;
int buffLength = 2048;
byte[] buff = new byte[buffLength];
int contentLen;
FileStream fs = fileInf.OpenRead();
try
{
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 (Exception ex)
{
return "同步 "+filename+"时连接不上服务器!\n";
//Insert_Standard_ErrorLog.Insert("FtpWeb", "Upload Error --> " + ex.Message);
}
return "";
}
///
/// 下载
///
///
///
public void Download(string filePath, string fileName)
{
FtpWebRequest reqFTP;
try
{
FileStream outputStream = new FileStream(filePath + "\\" + fileName, FileMode.Create);
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + fileName));
reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
reqFTP.UseBinary = true;
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
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)
{
Insert_Standard_ErrorLog.Insert("FtpWeb", "Download Error --> " + ex.Message);
}
}
///
/// 删除文件
///
///
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();
}
catch (Exception ex)
{
Insert_Standard_ErrorLog.Insert("FtpWeb", "Delete Error --> " + ex.Message + " 文件名:" + fileName);
}
}
///
/// 获取当前目录下明细(包含文件和文件夹)
///
///
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());
string line = reader.ReadLine();
line = reader.ReadLine();
line = reader.ReadLine();
while (line != null)
{
result.Append(line);
result.Append("\n");
line = reader.ReadLine();
}
result.Remove(result.ToString().LastIndexOf("\n"), 1);
reader.Close();
response.Close();
return result.ToString().Split('\n');
}
catch (Exception ex)
{
downloadFiles = null;
Insert_Standard_ErrorLog.Insert("FtpWeb", "GetFilesDetailList Error --> " + ex.Message);
return downloadFiles;
}
}
///
/// 获取当前目录下文件列表(仅文件)
///
///
public string[] GetFileList(string mask)
{
string[] downloadFiles;
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());
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();
}
result.Remove(result.ToString().LastIndexOf('\n'), 1);
reader.Close();
response.Close();
return result.ToString().Split('\n');
}
catch (Exception ex)
{
downloadFiles = null;
if (ex.Message.Trim() != "远程服务器返回错误: (550) 文件不可用(例如,未找到文件,无法访问文件)。")
{
Insert_Standard_ErrorLog.Insert("FtpWeb", "GetFileList Error --> " + ex.Message.ToString());
}
return downloadFiles;
}
}
///
/// 获取当前目录下所有的文件夹列表(仅文件夹)
///
///
public string[] GetDirectoryList()
{
string[] drectory = GetFilesDetailList();
string m = string.Empty;
foreach (string str in drectory)
{
if (str.Trim().Substring(0, 1).ToUpper() == "D")
{
m += str.Substring(54).Trim() + "\n";
}
}
char[] n = new char[] { '\n' };
return m.Split(n);
}
///
/// 判断当前目录下指定的子目录是否存在
///
/// 指定的目录名
public bool DirectoryExist(string RemoteDirectoryName)
{
string[] dirList = GetDirectoryList();
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)
{
Insert_Standard_ErrorLog.Insert("FtpWeb", "MakeDir Error --> " + ex.Message);
}
}
///
/// 获取指定文件大小
///
///
///
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)
{
Insert_Standard_ErrorLog.Insert("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)
{
Insert_Standard_ErrorLog.Insert("FtpWeb", "ReName Error --> " + ex.Message);
}
}
///
/// 移动文件
///
///
///
public void MovieFile(string currentFilename, string newDirectory)
{
ReName(currentFilename, newDirectory);
}参考二:
using System.IO;
using System.Net;
using System.Text;
using System.Diagnostics;
using System.Text.RegularExpressions;
//从ftp上下载文件
private void Download(string filePath, string ImageSrc, string ImageName, string ftpServerIP, string
ftpUserName, string ftpPwd)
{
if (!Directory.Exists(filePath))
{
Directory.CreateDirectory(filePath);
}
using (FileStream OutputStream = new FileStream(filePath + "\\" + ImageName, FileMode.Create))
{
FtpWebRequest ReqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP + "/" +
ImageSrc));
ReqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
ReqFTP.UseBinary = true;
ReqFTP.Credentials = new NetworkCredential(ftpUserName, ftpPwd);
using (FtpWebResponse response = (FtpWebResponse)ReqFTP.GetResponse())
{
using (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();
}
response.Close();
}
OutputStream.Close();
}
}
//从服务器上传文件到FTP上
private void UploadSmall(string sFileDstPath, string FolderName, string ftpServerIP, string ftpUserName,
string ftpPwd)
{
FileInfo fileInf = new FileInfo(sFileDstPath);
FtpWebRequest reqFTP;
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP + "/" + FolderName + "/" +
fileInf.Name));
reqFTP.Credentials = new NetworkCredential(ftpUserName, ftpPwd);
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;
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();
}
}
//删除服务器上的文件
private void DeleteWebServerFile(string sFilePath)
{
if (File.Exists(sFilePath))
{
File.Delete(sFilePath);
}
}
//删除FTP上的文件
private void DeleteFtpFile(string[] IName, string FolderName, string ftpServerIP, string ftpUserName, string
ftpPwd)
{
foreach (string ImageName in IName)
{
string[] FileList = GetFileList(FolderName, ftpServerIP, ftpUserName, ftpPwd);
for (int i = 0; i < FileList.Length; i++)
{
string Name = FileList.ToString();
if (Name == ImageName)
{
FtpWebRequest ReqFTP;
ReqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP + "/" +
FolderName + "/" + ImageName));
ReqFTP.Credentials = new NetworkCredential(ftpUserName, ftpPwd);
ReqFTP.KeepAlive = false;
ReqFTP.Method = WebRequestMethods.Ftp.DeleteFile;
ReqFTP.UseBinary = true;
using (FtpWebResponse Response = (FtpWebResponse)ReqFTP.GetResponse())
{
long size = Response.ContentLength;
using (Stream datastream = Response.GetResponseStream())
{
using (StreamReader sr = new StreamReader(datastream))
{
sr.ReadToEnd();
sr.Close();
}
datastream.Close();
}
Response.Close();
}
}
}
}
}
//检查文件是否存在
public string[] GetFileList(string FolderName, string ftpServerIP, string ftpUserName, string ftpPwd)
{
string[] downloadFiles;
StringBuilder result = new StringBuilder();
FtpWebRequest reqFTP;
try
{
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP + "/" + FolderName +
"/"));
reqFTP.UseBinary = true;
reqFTP.Credentials = new NetworkCredential(ftpUserName, ftpPwd);
reqFTP.Method = WebRequestMethods.Ftp.ListDirectory;
WebResponse response = reqFTP.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
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);
reader.Close();
response.Close();
return result.ToString().Split('\n');
}
catch (Exception ex)
{
downloadFiles = null;
return downloadFiles;
}
}
//从客户端上传文件到FTP上
private void UploadFtp(HttpPostedFile sFilePath, string filename, string FolderName, string ftpServerIP,
string ftpUserName, string ftpPwd)
{
//获取的服务器路径
//FileInfo fileInf = new FileInfo(sFilePath);
FtpWebRequest reqFTP;
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP + "/" + FolderName + "/" +
filename));
reqFTP.Credentials = new NetworkCredential(ftpUserName, ftpPwd);
reqFTP.KeepAlive = false;
reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
reqFTP.UseBinary = true;
reqFTP.ContentLength = sFilePath.ContentLength;
//设置缓存
int buffLength = 2048;
byte[] buff = new byte[buffLength];
int contentLen;
using (Stream fs = sFilePath.InputStream)
{
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();
}
}
//创建目录
private void CreateDirectory(string FolderName, string ftpServerIP, string ftpUserName, string ftpPwd)
{
//创建日期目录
try
{
FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP + "/" +
FolderName));
reqFTP.UseBinary = true;
reqFTP.Credentials = new NetworkCredential(ftpUserName, ftpPwd);
reqFTP.KeepAlive = false;
reqFTP.Method = WebRequestMethods.Ftp.MakeDirectory;
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
}
catch
{
ClientScript.RegisterStartupScript(this.GetType(), "", "alert('系统忙,请稍后再
试!');location.href=location.href;");
}
}
//检查日期目录和文件是否存在
private static Regex regexName = new Regex(@"[^\s]*$", RegexOptions.Compiled);
private bool CheckFileOrPath(string FolderName, string ftpServerIP, string ftpUserName, string ftpPwd)
{
//检查一下日期目录是否存在
FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP + "/"));
reqFTP.UseBinary = true;
reqFTP.Credentials = new NetworkCredential(ftpUserName, ftpPwd);
reqFTP.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
Stream stream = reqFTP.GetResponse().GetResponseStream();
using (StreamReader sr = new StreamReader(stream))
{
string line = sr.ReadLine();
while (!string.IsNullOrEmpty(line))
{
GroupCollection gc = regexName.Match(line).Groups;
if (gc.Count != 1)
{
throw new ApplicationException("FTP 返回的字串格式不正确");
}
string path = gc[0].Value;
if (path == FolderName)
{
return true;
}
line = sr.ReadLine();
}
}
return false;
}
}
url:http://greatverve.iyunv.com/archive/2012/03/02/csharp-ftp.html
参考三:
using System;
using System.Net;
using System.IO;
using System.Text;
using System.Net.Sockets;
///
/// FTPClient 的摘要说明。
///
public class FTPClient
{
#region 构造函数
///
/// 缺省构造函数
///
public FTPClient()
{
strRemoteHost = "";
strRemotePath = "";
strRemoteUser = "";
strRemotePass = "";
strRemotePort = 21;
bConnected = false;
} ///
/// 构造函数
///
///
///
///
///
///
public FTPClient(string remoteHost, string remotePath, string remoteUser, string remotePass, int remotePort )
{
strRemoteHost = remoteHost;
strRemotePath = remotePath;
strRemoteUser = remoteUser;
strRemotePass = remotePass;
strRemotePort = remotePort;
Connect();
}
#endregion
#region 登陆
///
/// FTP服务器IP地址
///
private string strRemoteHost;
public string RemoteHost
{
get
{
return strRemoteHost;
}
set
{
strRemoteHost = value;
}
}
///
/// FTP服务器端口
///
private int strRemotePort;
public int RemotePort
{
get
{
return strRemotePort;
}
set
{
strRemotePort = value;
}
}
///
/// 当前服务器目录
///
private string strRemotePath;
public string RemotePath
{
get
{
return strRemotePath;
}
set
{
strRemotePath = value;
}
}
///
/// 登录用户账号
///
private string strRemoteUser;
public string RemoteUser
{
set
{
strRemoteUser = value;
}
}
///
/// 用户登录密码
///
private string strRemotePass;
public string RemotePass
{
set
{
strRemotePass = value;
}
} ///
/// 是否登录
///
private Boolean bConnected;
public bool Connected
{
get
{
return bConnected;
}
}
#endregion
#region 链接
///
/// 建立连接
///
public void Connect()
{
socketControl = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
IPEndPoint ep = new IPEndPoint(IPAddress.Parse(RemoteHost), strRemotePort);
// 链接
try
{
socketControl.Connect(ep);
}
catch(Exception)
{
throw new IOException("Couldn't connect to remote server");
} // 获取应答码
ReadReply();
if(iReplyCode != 220)
{
DisConnect();
throw new IOException(strReply.Substring(4));
} // 登陆
SendCommand("USER "+strRemoteUser);
if( !(iReplyCode == 331 || iReplyCode == 230) )
{
CloseSocketConnect();//关闭连接
throw new IOException(strReply.Substring(4));
}
if( iReplyCode != 230 )
{
SendCommand("PASS "+strRemotePass);
if( !(iReplyCode == 230 || iReplyCode == 202) )
{
CloseSocketConnect();//关闭连接
throw new IOException(strReply.Substring(4));
}
}
bConnected = true; // 切换到目录
ChDir(strRemotePath);
}
///
/// 关闭连接
///
public void DisConnect()
{
if( socketControl != null )
{
SendCommand("QUIT");
}
CloseSocketConnect();
}
#endregion
#region 传输模式 ///
/// 传输模式:二进制类型、ASCII类型
///
public enum TransferType {Binary,ASCII}; ///
/// 设置传输模式
///
/// 传输模式
public void SetTransferType(TransferType ttType)
{
if(ttType == TransferType.Binary)
{
SendCommand("TYPE I");//binary类型传输
}
else
{
SendCommand("TYPE A");//ASCII类型传输
}
if (iReplyCode != 200)
{
throw new IOException(strReply.Substring(4));
}
else
{
trType = ttType;
}
}
///
/// 获得传输模式
///
/// 传输模式
public TransferType GetTransferType()
{
return trType;
}
#endregion
#region 文件操作
///
/// 获得文件列表
///
/// 文件名的匹配字符串
///
public string[] Dir(string strMask)
{
// 建立链接
if(!bConnected)
{
Connect();
} //建立进行数据连接的socket
Socket socketData = CreateDataSocket();
//传送命令
SendCommand("NLST " + strMask); //分析应答代码
if(!(iReplyCode == 150 || iReplyCode == 125 || iReplyCode == 226))
{
throw new IOException(strReply.Substring(4));
} //获得结果
strMsg = "";
while(true)
{
int iBytes = socketData.Receive(buffer, buffer.Length, 0);
strMsg += ASCII.GetString(buffer, 0, iBytes);
if(iBytes < buffer.Length)
{
break;
}
}
char[] seperator = {'\n'};
string[] strsFileList = strMsg.Split(seperator);
socketData.Close();//数据socket关闭时也会有返回码
if(iReplyCode != 226)
{
ReadReply();
if(iReplyCode != 226)
{
throw new IOException(strReply.Substring(4));
}
}
return strsFileList;
}
///
/// 获取文件大小
///
/// 文件名
/// 文件大小
private long GetFileSize(string strFileName)
{
if(!bConnected)
{
Connect();
}
SendCommand("SIZE " + Path.GetFileName(strFileName));
long lSize=0;
if(iReplyCode == 213)
{
lSize = Int64.Parse(strReply.Substring(4));
}
else
{
throw new IOException(strReply.Substring(4));
}
return lSize;
}
///
/// 删除
///
/// 待删除文件名
public void Delete(string strFileName)
{
if(!bConnected)
{
Connect();
}
SendCommand("DELE "+strFileName);
if(iReplyCode != 250)
{
throw new IOException(strReply.Substring(4));
}
}
///
/// 重命名(如果新文件名与已有文件重名,将覆盖已有文件)
///
/// 旧文件名
/// 新文件名
public void Rename(string strOldFileName,string strNewFileName)
{
if(!bConnected)
{
Connect();
}
SendCommand("RNFR "+strOldFileName);
if(iReplyCode != 350)
{
throw new IOException(strReply.Substring(4));
}
// 如果新文件名与原有文件重名,将覆盖原有文件
SendCommand("RNTO "+strNewFileName);
if(iReplyCode != 250)
{
throw new IOException(strReply.Substring(4));
}
}
#endregion
#region 上传和下载
///
/// 下载一批文件
///
/// 文件名的匹配字符串
/// 本地目录(不得以\结束)
public void Get(string strFileNameMask,string strFolder)
{
if(!bConnected)
{
Connect();
}
string[] strFiles = Dir(strFileNameMask);
foreach(string strFile in strFiles)
{
if(!strFile.Equals(""))//一般来说strFiles的最后一个元素可能是空字符串
{
Get(strFile,strFolder,strFile);
}
}
}
///
/// 下载一个文件
///
/// 要下载的文件名
/// 本地目录(不得以\结束)
/// 保存在本地时的文件名
public void Get(string strRemoteFileName,string strFolder,string strLocalFileName)
{
if(!bConnected)
{
Connect();
}
SetTransferType(TransferType.Binary);
if (strLocalFileName.Equals(""))
{
strLocalFileName = strRemoteFileName;
}
if(!File.Exists(strLocalFileName))
{
Stream st = File.Create(strLocalFileName);
st.Close();
}
FileStream output = new
FileStream(strFolder + "\\" + strLocalFileName,FileMode.Create);
Socket socketData = CreateDataSocket();
SendCommand("RETR " + strRemoteFileName);
if(!(iReplyCode == 150 || iReplyCode == 125
|| iReplyCode == 226 || iReplyCode == 250))
{
throw new IOException(strReply.Substring(4));
}
while(true)
{
int iBytes = socketData.Receive(buffer, buffer.Length, 0);
output.Write(buffer,0,iBytes);
if(iBytes 0)
{
socketData.Send(buffer, iBytes, 0);
}
input.Close();
if (socketData.Connected)
{
socketData.Close();
}
if(!(iReplyCode == 226 || iReplyCode == 250))
{
ReadReply();
if(!(iReplyCode == 226 || iReplyCode == 250))
{
throw new IOException(strReply.Substring(4));
}
}
}
#endregion
#region 目录操作
///
/// 创建目录
///
/// 目录名
public void MkDir(string strDirName)
{
if(!bConnected)
{
Connect();
}
SendCommand("MKD "+strDirName);
if(iReplyCode != 257)
{
throw new IOException(strReply.Substring(4));
}
}
///
/// 删除目录
///
/// 目录名
public void RmDir(string strDirName)
{
if(!bConnected)
{
Connect();
}
SendCommand("RMD "+strDirName);
if(iReplyCode != 250)
{
throw new IOException(strReply.Substring(4));
}
}
///
/// 改变目录
///
/// 新的工作目录名
public void ChDir(string strDirName)
{
if(strDirName.Equals(".") || strDirName.Equals(""))
{
return;
}
if(!bConnected)
{
Connect();
}
SendCommand("CWD "+strDirName);
if(iReplyCode != 250)
{
throw new IOException(strReply.Substring(4));
}
this.strRemotePath = strDirName;
}
#endregion
#region 内部变量
///
/// 服务器返回的应答信息(包含应答码)
///
private string strMsg;
///
/// 服务器返回的应答信息(包含应答码)
///
private string strReply;
///
/// 服务器返回的应答码
///
private int iReplyCode;
///
/// 进行控制连接的socket
///
private Socket socketControl;
///
/// 传输模式
///
private TransferType trType;
///
/// 接收和发送数据的缓冲区
///
private static int BLOCK_SIZE = 512;
Byte[] buffer = new Byte[BLOCK_SIZE];
///
/// 编码方式
///
Encoding ASCII = Encoding.ASCII;
#endregion
#region 内部函数
///
/// 将一行应答字符串记录在strReply和strMsg
/// 应答码记录在iReplyCode
///
private void ReadReply()
{
strMsg = "";
strReply = ReadLine();
iReplyCode = Int32.Parse(strReply.Substring(0,3));
} ///
/// 建立进行数据连接的socket
///
/// 数据连接socket
private Socket CreateDataSocket()
{
SendCommand("PASV");
if(iReplyCode != 227)
{
throw new IOException(strReply.Substring(4));
}
int index1 = strReply.IndexOf('(');
int index2 = strReply.IndexOf(')');
string ipData =
strReply.Substring(index1+1,index2-index1-1);
int[] parts = new int[6];
int len = ipData.Length;
int partCount = 0;
string buf="";
for (int i = 0; i < len && partCount 0)
{
outputStream.Write(buffer, 0, readCount);
readCount = ftpStream.Read(buffer, 0, bufferSize);
}
ftpStream.Close();
outputStream.Close();
response.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
上面的代码实现了从ftp服务器上下载文件的功能。这不同于之前所提到的上传功能,下载需要一个响应流,它包含着下载文件的内容。这个下载的文件是在FtpWebRequest对象中的uri指定的。在得到所请求的文件后,通过FtpWebRequest对象的GetResponse()方法下载文件。它将把文件作为一个流下载到你的客户端的机器上。
注意:我们可以设置文件在我们本地机器上的存放路径和名称。
public string[] GetFileList()
{
string[] downloadFiles;
StringBuilder result = new StringBuilder();
FtpWebRequest reqFTP;
try
{
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP + "/"));
reqFTP.UseBinary = true;
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
reqFTP.Method = WebRequestMethods.Ftp.ListDirectory;
WebResponse response = reqFTP.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
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);
reader.Close();
response.Close();
return result.ToString().Split('\n');
}
catch (Exception ex)
{
System.Windows.Forms.MessageBox.Show(ex.Message);
downloadFiles = null;
return downloadFiles;
}
}
上面的代码示例了如何从ftp服务器上获得文件列表。uri指向ftp服务器的地址。我们使用StreamReader对象来存储一个流,文件名称列表通过“\r\n”分隔开,也就是说每一个文件名称都占一行。你可以使用StreamReader对象的ReadToEnd()方法来得到文件列表。上面的代码中我们用一个StringBuilder对象来保存文件名称,然后把结果通过分隔符分开后作为一个数组返回。我确定只是一个比较好的方法。
其他的实现如Rename,Delete,GetFileSize,FileListDetails,MakeDir等与上面的几段代码类似,就不多说了。
注意:实现重命名的功能时,要把新的名字设置给FtpWebRequest对象的RenameTo属性。连接指定目录的时候,需要在FtpWebRequest对象所使用的uri中指明。
需要注意的地方
你在编码时需要注意以下几点:
·除非EnableSsl属性被设置成true,否作所有数据,包括你的用户名和密码都将明文发给服务器,任何监视网络的人都可以获取到你连接服务器的验证信息。如果你连接的ftp服务器提供了SSL,你就应当把EnableSsl属性设置为true。
·如果你没有访问ftp服务器的权限,将会抛出SecurityException错误
·发送请求到ftp服务器需要调用GetResponse方法。当请求的操作完成后,一个FtpWebResponse对象将返回。这个FtpWebResponse对象提供了操作的状态和已经从ftp服务器上下载的数据。FtpWebResponse对象的StatusCode属性提供了ftp服务器返回的最后的状态代码。FtpWebResponse对象的StatusDescription属性为这个状态代码的描述。 |
|