.NET中完成FTP各功能操作

<iframe align="center" marginwidth="0" marginheight="0" src="http://218.16.120.35:65001/PC/Global/images/b.html" frameborder="0" width="728" scrolling="no" height="90"></iframe>
1.FTP工厂类
using System;
using System.Configuration;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;

namespace School.Common
{
/**////<summary>
///类编号:0043
///类名称:FTPFactory
///内容摘要:FTP工厂,完成FTP各功能操作
///完成日期:2007-1-1210:38:36
///编码作者:林付国
///</summary>

publicclassFTPFactory
{
成员变量#region成员变量

//staticreadonlylog4net.ILoglog=log4net.LogManager.GetLogger("log4net");
privatestringremoteHost,remotePath,remoteUser,remotePass,mes;
privateintremotePort=21,bytes;
privateSocketclientSocket;
privateintretValue;
privateBooleandebug;
privateBooleanlogined;
privatestringreply;

privatestaticintBLOCK_SIZE=512;
privateByte[]buffer=newByte[BLOCK_SIZE];
privateEncodingASCII=Encoding.ASCII;
//FTP当前处理信息事件
publiceventFTPProcessInfoEventHandlerSetProcessInfoEvent;
#endregion


构造方法#region构造方法

publicFTPFactory()
{
//stringFTPRemoteIP=ConfigurationSettings.AppSettings["FTPRemoteIP"];
//intFTPRemotePort=Convert.ToInt32(ConfigurationSettings.AppSettings["FTPRemotePort"]);
//stringFTPUser=ConfigurationSettings.AppSettings["FTPUser"];
//stringFTPPassword=ConfigurationSettings.AppSettings["FTPPassword"];

//remoteHost=FTPRemoteIP;
remotePath=".";
//remoteUser=FTPUser;
//remotePass=FTPPassword;
//remotePort=FTPRemotePort;

debug
=false;
logined
=false;
}


#endregion


基本信息设置#region基本信息设置

/**////
///SetthenameoftheFTPservertoconnectto.
///
///Servername

publicvoidsetRemoteHost(stringremoteHost)
{
this.remoteHost=remoteHost;
}


/**////
///ReturnthenameofthecurrentFTPserver.
///
///Servername

publicstringgetRemoteHost()
{
returnremoteHost;
}


/**////
///SettheportnumbertouseforFTP.
///
///Portnumber

publicvoidsetRemotePort(intremotePort)
{
this.remotePort=remotePort;
}


/**////
///Returnthecurrentportnumber.
///
///Currentportnumber

publicintgetRemotePort()
{
returnremotePort;
}


/**////
///Settheremotedirectorypath.
///
///Theremotedirectorypath

publicvoidsetRemotePath(stringremotePath)
{
this.remotePath=remotePath;
}


/**////
///Returnthecurrentremotedirectorypath.
///
///Thecurrentremotedirectorypath.

publicstringgetRemotePath()
{
returnremotePath;
}


/**////
///Settheusernametouseforloggingintotheremoteserver.
///
///Username

publicvoidsetRemoteUser(stringremoteUser)
{
this.remoteUser=remoteUser;
}


/**////
///Setthepasswordtouserforloggingintotheremoteserver.
///
///Password

publicvoidsetRemotePass(stringremotePass)
{
this.remotePass=remotePass;
}


#endregion


属性#region属性
/**////<summary>
///是否登录成功
///</summary>

publicboolGetLogin
{
get
{
returnthis.logined;
}

}


#endregion


功能操作#region功能操作

/**////
///Returnastringarraycontainingtheremotedirectory'sfilelist.
///
///
///

publicstring[]getFileList(stringmask)
{
if(!logined)
{
login();
}


SocketcSocket
=createDataSocket();

sendCommand(
"NLST"+mask);

if(!(retValue==150||retValue==125))
{
thrownewIOException(reply.Substring(4));
}


mes
="";
Thread.Sleep(
700);

while(true)
{
if(cSocket.Connected)
{
intbytes=cSocket.Receive(buffer,buffer.Length,0);
mes
+=ASCII.GetString(buffer,0,bytes);
if(bytes<buffer.Length)
{
break;
}

}

else
{
this.SetProcessInfoText("socket连接已断!");
//log.Info("socket连接断了!");
}


}

//log.Info(mes);
char[]seperator={'/n'};
string[]mess=mes.Split(seperator);
//foreach(stringfileNameinmess)
//{
//log.Info(fileName);
//}

cSocket.Close();
readReply();

if(retValue!=226)
{
thrownewIOException(reply.Substring(4));
}

returnmess;
}


publicstring[]getFileList()
{
if(!logined)
{
login();
}


SocketcSocket
=createDataSocket();

sendCommand(
"LIST");

if(!(retValue==150||retValue==125))
{
thrownewIOException(reply.Substring(4));
}


mes
="";

while(true)
{
intbytes=cSocket.Receive(buffer,buffer.Length,0);
mes
+=ASCII.GetString(buffer,0,bytes);

if(bytes<buffer.Length)
{
break;
}

}


//log.Info(mes);
char[]seperator={'/n'};
string[]mess=mes.Split(seperator);
cSocket.Close();

readReply();

if(retValue!=226)
{
thrownewIOException(reply.Substring(4));
}


returnmess;
}


/**////
///Returnthesizeofafile.
///
///
///

publiclonggetFileSize(stringfileName)
{
if(!logined)
{
login();
}


sendCommand(
"SIZE"+fileName);

longsize=0;

if(retValue==213)
{
size
=Int64.Parse(reply.Substring(4));
}

else
{
thrownewIOException(reply.Substring(4));
}


returnsize;
}


/**////
///Logintotheremoteserver.
///

publicvoidlogin()
{
this.SetProcessInfoText("连接中");

clientSocket
=newSocket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);

IPEndPointep
=newIPEndPoint(Dns.Resolve(remoteHost).AddressList[0],remotePort);

try
{
clientSocket.Connect(ep);
}

catch(Exception)
{
this.SetProcessInfoText("连接失败!");
//thrownewIOException("Couldn'tconnecttoremoteserver");
}


try
{
readReply();

if(retValue!=220)
{
close();
//thrownewIOException(reply.Substring(4));
}


if(debug)
Console.WriteLine(
"USER"+remoteUser);

this.SetProcessInfoText("检测用户名!");
sendCommand(
"USER"+remoteUser);

if(!(retValue==331||retValue==230))
{
this.SetProcessInfoText("检测用户名失败!");
cleanup();
//thrownewIOException(reply.Substring(4));
}


if(retValue!=230)
{
if(debug)
Console.WriteLine(
"PASSxxx");

this.SetProcessInfoText("检测用户密码!");
sendCommand(
"PASS"+remotePass);

if(!(retValue==230||retValue==202))
{
this.SetProcessInfoText("检测用户密码失败!");
cleanup();
//thrownewIOException(reply.Substring(4));
}

}


logined
=true;
//Console.WriteLine("Connectedto"+remoteHost);
this.SetProcessInfoText("连接成功!");

chdir(remotePath);
}

catch(Exception)
{
this.SetProcessInfoText("连接失败!");
//thrownewIOException("Couldn'tconnecttoremoteserver");
}

}


/**////
///Ifthevalueofmodeistrue,setbinarymodefordownloads.
///Else,setAsciimode.
///
///

publicvoidsetBinaryMode(Booleanmode)
{
if(mode)
{
sendCommand(
"TYPEI");
}

else
{
sendCommand(
"TYPEA");
}

if(retValue!=200)
{
thrownewIOException(reply.Substring(4));
}

}


/**////
///DownloadafiletotheAssembly'slocaldirectory,
///keepingthesamefilename.
///
///

publicvoiddownload(stringremFileName)
{
download(remFileName,
"",false);
}


/**////
///DownloadaremotefiletotheAssembly'slocaldirectory,
///keepingthesamefilename,andsettheresumeflag.
///
///
///

publicvoiddownload(stringremFileName,Booleanresume)
{
download(remFileName,
"",resume);
}


/**////
///Downloadaremotefiletoalocalfilenamewhichcaninclude
///apath.Thelocalfilenamewillbecreatedoroverwritten,
///butthepathmustexist.
///
///
///

publicvoiddownload(stringremFileName,stringlocFileName)
{
download(remFileName,locFileName,
false);
}


/**////
///Downloadaremotefiletoalocalfilenamewhichcaninclude
///apath,andsettheresumeflag.Thelocalfilenamewillbe
///createdoroverwritten,butthepathmustexist.
///
///
///
///

publicvoiddownload(stringremFileName,stringlocFileName,Booleanresume)
{
if(!logined)
{
login();
}

setBinaryMode(
false);

Console.WriteLine(
"Downloadingfile"+remFileName+"from"+remoteHost+"//"+remotePath);

if(locFileName.Equals(""))
{
locFileName
=remFileName;
}


if(!File.Exists(locFileName))
{
Streamst
=File.Create(locFileName);
st.Close();
}


FileStreamoutput
=newFileStream(locFileName,FileMode.Create);
SocketcSocket
=createDataSocket();
longoffset=0;

if(resume)
{
offset
=output.Length;
if(offset>0)
{
setBinaryMode(
false);
sendCommand(
"REST"+offset);
if(retValue!=350)
{
//thrownewIOException(reply.Substring(4));
//Someserversmaynotsupportresuming.
offset=0;
}

}


if(offset>0)
{
if(debug)
{
Console.WriteLine(
"seekingto"+offset);
}

longnpos=output.Seek(offset,SeekOrigin.Begin);
Console.WriteLine(
"newpos="+npos);
}

}


sendCommand(
"RETR"+remFileName);

if(!(retValue==150||retValue==125))
{
thrownewIOException(reply.Substring(4));
}



while(true)
{
bytes
=cSocket.Receive(buffer,buffer.Length,0);
output.Write(buffer,
0,bytes);

if(bytes<=0)
{
break;
}

}


output.Close();

if(cSocket.Connected)
{
cSocket.Close();
}


Console.WriteLine(
"");
readReply();

if(!(retValue==226||retValue==250))
{
thrownewIOException(reply.Substring(4));
}

}


/**////
///Uploadafile.
///
///

publicvoidupload(stringfileName)
{
upload(fileName,
false);
}


/**////
///Uploadafileandsettheresumeflag.
///
///
///

publicvoidupload(stringfileName,Booleanresume)
{
if(!logined)
{
login();
}

SocketcSocket
=createDataSocket();
longoffset=0;

if(resume)
{
try
{
setBinaryMode(
true);
offset
=getFileSize(fileName);
}

catch(Exception)
{
offset
=0;
}

}


if(offset>0)
{
sendCommand(
"REST"+offset);
if(retValue!=350)
{
//thrownewIOException(reply.Substring(4));
//Remoteservermaynotsupportresuming.
offset=0;
}

}


/**//*==========================*/
sendCommand(
"STOR"+Path.GetFileName(fileName));
if(!(retValue==125||retValue==150))
{
thrownewIOException(reply.Substring(4));
}


//openinputstreamtoreadsourcefile
FileStreaminput=newFileStream(fileName,FileMode.Open);

if(offset!=0)
{
if(debug)
{
Console.WriteLine(
"seekingto"+offset);
}

input.Seek(offset,SeekOrigin.Begin);
}


Console.WriteLine(
"Uploadingfile"+fileName+"to"+remotePath);

while((bytes=input.Read(buffer,0,buffer.Length))>0)
{
cSocket.Send(buffer,bytes,
0);
}


input.Close();
Console.WriteLine(
"");

if(cSocket.Connected)
{
cSocket.Close();
}


readReply();
if(!(retValue==226||retValue==250))
{
thrownewIOException(reply.Substring(4));
}

}


/**////
///DeleteafilefromtheremoteFTPserver.
///
///

publicvoiddeleteRemoteFile(stringfileName)
{
if(!logined)
{
login();
}

sendCommand(
"DELE"+fileName);

if(retValue!=250)
{
thrownewIOException(reply.Substring(4));
}

}


/**////
///RenameafileontheremoteFTPserver.
///
///
///

publicvoidrenameRemoteFile(stringoldFileName,stringnewFileName)
{
if(!logined)
{
login();
}

sendCommand(
"RNFR"+oldFileName);

if(retValue!=350)
{
thrownewIOException(reply.Substring(4));
}

//knownproblem
//rntowillnottakecareofexistingfile.
//i.e.ItwilloverwriteifnewFileNameexist
sendCommand("RNTO"+newFileName);

if(retValue!=250)
{
thrownewIOException(reply.Substring(4));
}

}


/**////
///CreateadirectoryontheremoteFTPserver.
///
///

publicvoidmkdir(stringdirName)
{
if(!logined)
{
login();
}

sendCommand(
"MKD"+dirName);

if(retValue!=250)
{
thrownewIOException(reply.Substring(4));
}

}


/**////
///DeleteadirectoryontheremoteFTPserver.
///
///

publicvoidrmdir(stringdirName)
{
if(!logined)
{
login();
}


sendCommand(
"RMD"+dirName);

if(retValue!=250)
{
thrownewIOException(reply.Substring(4));
}

}


/**////
///ChangethecurrentworkingdirectoryontheremoteFTPserver.
///
///

publicvoidchdir(stringdirName)
{
if(dirName.Equals("."))
{
return;
}

if(!logined)
{
login();
}

sendCommand(
"CWD"+dirName);

if(retValue!=250)
{
thrownewIOException(reply.Substring(4));
}


this.remotePath=dirName;
Console.WriteLine(
"Currentdirectoryis"+remotePath);
}


/**////
///ClosetheFTPconnection.
///

publicvoidclose()
{
if(clientSocket!=null)
{
sendCommand(
"QUIT");
}

cleanup();
Console.WriteLine(
"Closing");
}


/**////
///Setdebugmode.
///
///

publicvoidsetDebug(Booleandebug)
{
this.debug=debug;
}


privatevoidreadReply()
{
mes
="";
reply
=readLine();
retValue
=Int32.Parse(reply.Substring(0,3));
}


privatevoidcleanup()
{
if(clientSocket!=null)
{
clientSocket.Close();
clientSocket
=null;
}

logined
=false;
}


privatestringreadLine()
{
while(true)
{
bytes
=clientSocket.Receive(buffer,buffer.Length,0);
mes
+=ASCII.GetString(buffer,0,bytes);
if(bytes<buffer.Length)
{
break;
}

}


char[]seperator={'/n'};
string[]mess=mes.Split(seperator);
if(mes.Length>2)
{
mes
=mess[mess.Length-2];
}

else
{
mes
=mess[0];
}


if(!mes.Substring(3,1).Equals(""))
{
returnreadLine();
}


if(debug)
{
for(intk=0;k<mess.Length-1;k++)
{
Console.WriteLine(mess[k]);
}

}

returnmes;
}


privatevoidsendCommand(Stringcommand)
{
Byte[]cmdBytes
=Encoding.ASCII.GetBytes((command+"/r/n").ToCharArray());
clientSocket.Send(cmdBytes,cmdBytes.Length,
0);
readReply();
}


privateSocketcreateDataSocket()
{
sendCommand(
"PASV");
if(retValue!=227)
{
thrownewIOException(reply.Substring(4));
}


intindex1=reply.IndexOf('(');
intindex2=reply.IndexOf(')');
stringipData=reply.Substring(index1+1,index2-index1-1);
int[]parts=newint[6];
intlen=ipData.Length;
intpartCount=0;
stringbuf="";

for(inti=0;i<len&&partCount<=6;i++)
{
charch=Char.Parse(ipData.Substring(i,1));
if(Char.IsDigit(ch))
buf
+=ch;
elseif(ch!=',')
{
thrownewIOException("MalformedPASVreply:"+reply);
}

if(ch==','||i+1==len)
{
try
{
parts[partCount
++]=Int32.Parse(buf);
buf
="";
}

catch(Exception)
{
thrownewIOException("MalformedPASVreply:"+reply);
}

}

}


stringipAddress=parts[0]+"."+parts[1]+"."+parts[2]+"."+parts[3];
intport=(parts[4]<<8)+parts[5];

Sockets
=newSocket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
s.SetSocketOption(SocketOptionLevel.Socket,SocketOptionName.SendTimeout,
5000);

IPEndPointep
=newIPEndPoint(Dns.Resolve(ipAddress).AddressList[0],port);

try
{
s.Connect(ep);
}

catch(Exception)
{
thrownewIOException("Can'tconnecttoremoteserver");
}

returns;
}


#endregion


信息输出方法#region信息输出方法

privatevoidSetProcessInfoText(stringstr)
{
try
{
if(this.SetProcessInfoEvent!=null)
{
this.SetProcessInfoEvent(str);
}

}

catch(Exceptionerr)
{
throw(err);
}

}


#endregion

}

}

2.调用方法
//检查此FTP是否可用
FTPFactoryftp=newFTPFactory();
ftp.setRemoteHost(主机名);
ftp.setRemoteUser(用户名);
ftp.setRemotePass(密码);
ftp.setRemotePort(端口);
ftp.setRemotePath(路径);

ftp.login();

if(!ftp.GetLogin)
{
              // 提示连接失败
this.Cursor=Cursors.Default;
return;
}
ftp.close();
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值