📄 ftpclient.cs
字号:
break;
default:
m_strError = "Sorry !!! server type '" + m_strServerType + "' is not recognized by FTP Explorer" ;
break;
}
return l_dtFileList;
}
/// <summary>
/// Executes a Ftp Data Command
/// </summary>
/// <param name="l_strCommand">Command string</param>
/// <param name="l_strOutputData">Output string</param>
/// <returns>1 if success, else 0</returns>
private int ExecuteDataCommand(string l_strCommand,out string l_strOutputData){
TcpListener l_FTPListener = null;
Socket l_ClientDataSocket = null;
int l_iRetval = 0, l_iDataPort = 0;
try {
l_strOutputData = "";
l_FTPListener = new TcpListener(0);
Trace.WriteLine("Inside ExecuteDataCommand()");
l_FTPListener.Start();
IPEndPoint pt = (IPEndPoint) l_FTPListener.LocalEndpoint;
l_iDataPort = pt.Port;
Trace.WriteLine("Port Number :" + l_iDataPort);
string l_strOutput = "";
string l_strPortParams = GetPortParameters(l_iDataPort);
/* PORT command */
string l_strPortCommand = "PORT " + l_strPortParams + "\r\n";
l_iRetval = ExecuteCommand(l_strPortCommand,ref l_strOutput);
Trace.WriteLine("Port Command :" + l_iRetval + ":" + l_strOutput);
if ( l_iRetval == 0 ) {
return l_iRetval;
}
/* Execute the actual command here */
l_iRetval = ExecuteCommand(l_strCommand,ref l_strOutput);
Trace.WriteLine("LIST Command :" + l_iRetval + ":" + l_strOutput);
/*if ( l_iRetval == 0 ) {
return l_iRetval;
}*/
Trace.WriteLine("Before Accept Socket()");
/* Accept Client connection here */
l_ClientDataSocket = l_FTPListener.AcceptSocket();
/*IPEndPoint ep = (IPEndPoint) l_FTPListener.LocalEndpoint;
int iiiiiii = ep.Port;*/
Trace.WriteLine("After Accept Socket()");
l_ClientDataSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout,m_iSendTimeOut);
l_ClientDataSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout,m_iRecvTimeOut);
Byte[] l_bRecvData = new Byte[1024];
l_strOutput = "";
string l_strTemp = "";
l_iRetval = 0;
/* Loop through and Receive all the data */
//for ( ; (l_iRetval = l_ClientDataSocket.Receive(l_bRecvData,5119,0)) > 0 ; ) {
Trace.WriteLine("Before for()");
Thread.Sleep(1000);
Trace.WriteLine("Before for()1");
for ( ; l_ClientDataSocket.Available > 0 ; ) {
l_iRetval = l_ClientDataSocket.Receive(l_bRecvData,1023,0);
Trace.WriteLine("Inside for() :" + l_iRetval);
l_strTemp = Encoding.ASCII.GetString(l_bRecvData,0,l_iRetval);
l_strOutput += l_strTemp;
}
Trace.WriteLine("After for()");
l_ClientDataSocket.Shutdown(SocketShutdown.Both);
l_ClientDataSocket.Close();
l_ClientDataSocket = null;
l_strOutputData = l_strOutput;
l_iRetval = 1;
}
catch ( SocketException e1){
Trace.WriteLine("Inside Exception1" + e1.Message);
m_strError = e1.Message;
l_strOutputData = "";
return 0;
}
catch ( Exception e ) {
Trace.WriteLine("Inside Exception2" + e.Message);
m_strError = e.Message;
l_strOutputData = "";
return 0;
}
finally{
Trace.WriteLine("Inside Finally");
if ( l_FTPListener != null ) {
l_FTPListener.Stop();
l_FTPListener = null;
}
if ( l_ClientDataSocket != null ) {
l_ClientDataSocket.Shutdown(SocketShutdown.Both);
l_ClientDataSocket.Close();
l_ClientDataSocket = null;
}
}
return l_iRetval;
}
/// <summary>
/// Generate Port number
/// </summary>
/// <returns>Returns newly generated port number</returns>
private int GetPort(){
if ( m_iDataPort > 30000 ) {
m_iDataPort = 10000;
}
return m_iDataPort++;
}
/// <summary>
/// Get PORT parameters
/// </summary>
/// <param name="l_iPort">Input Port number</param>
/// <returns>Output string</returns>
private string GetPortParameters(int l_iPort){
string l_strLocalMachine = Dns.GetHostName();
IPEndPoint l_IPServer;
IPHostEntry l_localHost = Dns.Resolve(l_strLocalMachine);
IPAddress l_IPAddress = l_localHost.AddressList[0];
l_IPServer = new IPEndPoint(l_IPAddress,l_iPort);
string l_strIPAddress = l_IPAddress.ToString();
l_strIPAddress = l_strIPAddress.Replace('.',',');
int l_iParam1 = ( 0xff00 & l_iPort ) >> 8;
int l_iParam2 = ( 0xff & l_iPort ) ;
string l_strPortParam = l_strIPAddress + "," + l_iParam1 + "," + l_iParam2;
return l_strPortParam;
}
/// <summary>
///
/// </summary>
/// <param name="l_arrFiles"></param>
/// <returns></returns>
private DataTable ParseStringArrayForUnix(string[] l_arrFiles){
DataTable l_dtFileList = new DataTable(m_strCurrentWorkingDir);
l_dtFileList.Columns.Add(new DataColumn("FileType",typeof(int)));
l_dtFileList.Columns.Add(new DataColumn("FileName",typeof(string)));
l_dtFileList.Columns.Add(new DataColumn("FilePath",typeof(string)));
l_dtFileList.Columns.Add(new DataColumn("CreatedDate",typeof(string)));
l_dtFileList.Columns.Add(new DataColumn("FileSize",typeof(int)));
l_dtFileList.Columns.Add(new DataColumn("FileOwner",typeof(string)));
l_dtFileList.Columns.Add(new DataColumn("FileGroup",typeof(string)));
string l_strcurFile = "";
int l_iFileCount = l_arrFiles.Length;
int l_iLineCount = 0;
char[] l_arrchSep = new char[2];
l_arrchSep[0] = ' ';
l_arrchSep[1] = '\0';
foreach(object obj in l_arrFiles) {
l_strcurFile = (string) obj;
/* If first line then parse for length */
if ( l_iLineCount == 0 ) {
l_iLineCount++;
continue;
}
else {
/* Parse for file info */
string[] l_strarrFields = SplitStringForUnix(l_strcurFile);
if (l_strarrFields.Length == 1 || l_strarrFields[0].Length <= 0 ) {
/* If the element is empty, do not attempt to parse it */
l_iLineCount++;
continue;
}
/* Each field is now in l_strarrFields */
DataRow l_drNew = l_dtFileList.NewRow();
if ( GetFileInfoForUnix(l_strarrFields,ref l_drNew) == 1 ){
if ( l_drNew != null ) {
l_dtFileList.Rows.Add(l_drNew);
}
}
}
l_iLineCount++;
}
return l_dtFileList;
}
/// <summary>
///
/// </summary>
/// <param name="l_strarrFields"></param>
/// <param name="l_drNew"></param>
/// <returns></returns>
private int GetFileInfoForUnix(string[] l_strarrFields,ref DataRow l_drNew){
string l_strField = "";
string l_strFileName = "" ,l_strFilePath = "" ,l_strDateCreated = "";
string l_strFileOwner = "",l_strFileGroup = "";
int l_iFileType = 0,l_iFileSize = 0;
int l_iCount = 0,l_iErrFlag = 0;
char l_chTemp = '\0';
foreach(object obj in l_strarrFields) {
l_strField = (string) obj;
if (l_strField.Length <= 0 ) {
l_iErrFlag = 1;
break;
}
switch( l_iCount) {
case 0: /* File Type */
l_chTemp = l_strField[0];
if ( l_chTemp == '-' ) {
/* Normal File */
l_iFileType = 1;
}
else if ( l_chTemp == 'd') {
/* Directory */
l_iFileType = 2;
}
else if ( l_chTemp == 'c' ) {
/* System file */
l_iFileType = 3;
}
else {
/* Unknown file type */
l_iFileType = 0;
}
break;
case 1 : /* File Links */
break;
case 2 : /* File Owner */
l_strFileOwner = l_strField;
break;
case 3 : /* File group */
l_strFileGroup = l_strField;
break;
case 4 : /* File size in bytes */
l_iFileSize = int.Parse(l_strField);
break;
case 5 : /* Date created ( contains month in mmm format ) */
l_strDateCreated = l_strField;
break;
case 6 : /* Date created ( contains day in dd format ) */
l_strDateCreated += " " + l_strField;
break;
case 7 : /* Date created ( contains time in HH:SS or year in YYYY format ) */
l_strDateCreated += " " + l_strField;
break;
case 8 : /* File name */
l_strFileName = l_strField;
l_strFileName = l_strFileName.Trim();
if (l_strFileName.Length == 0 ) {
l_strFileName = "<unknown>";
}
break;
case 9 :
break;
} /* End of switch statement */
l_iCount++;
} /* End of for */
/* If error occured while parsing return null and ignore this element */
if (l_iErrFlag == 1 ) {
return 0;
}
if ( l_strFileName == "." || l_strFileName == ".." ){
l_drNew = null;
return 0;
}
if ( m_strCurrentWorkingDir.EndsWith("/") == true ){
l_strFilePath = m_strCurrentWorkingDir + l_strFileName;
}
else {
l_strFilePath = m_strCurrentWorkingDir + "/" + l_strFileName;
}
l_drNew[0] = l_iFileType;
l_drNew[1] = l_strFileName;
l_drNew[2] = l_strFilePath;
l_drNew[3] = l_strDateCreated;
l_drNew[4] = l_iFileSize;
l_drNew[5] = l_strFileOwner;
l_drNew[6] = l_strFileGroup;
return 1;
}
/// <summary>
/// This function takes a string and squeezes more than
/// one space characters into one character and
/// then splits into array and returns back to the caller
/// </summary>
/// <param name="l_strInString">Input String</param>
/// <returns>Output string in an array</returns>
private string[] SplitStringForUnix(string l_strInString){
string[] l_strarrOut = new string[9];
string l_strTemp = "";
char[] l_arrchSep = new char[2];
l_arrchSep[0] = ' ';
l_arrchSep[1] = '\0';
/* Squeeze more spaces into single space character */
int l_iCount = 0,l_iLen = l_strInString.Length;
for ( ; l_iCount < l_iLen ; l_iCount++ ) {
if ( l_strInString[l_iCount] == ' ' ) {
l_strTemp += l_strInString[l_iCount];
if ( l_strInString[l_iCount + 1] == ' ' ) {
for ( l_iCount++ ; l_strInString[l_iCount] == ' '; l_iCount++ ) ;
l_strTemp += l_strInString[l_iCount];
}
}
else {
l_strTemp += l_strInString[l_iCount];
}
}
l_strarrOut = l_strTemp.Split(l_arrchSep);
return l_strarrOut;
}
/// <summary>
/// Disconnect from FTP server
/// </summary>
/// <returns>1 if success, else 0</returns>
public int Disconnect(){
if ( m_ClientSocket == null ) {
m_strError = "Sockets not Initialized";
return 0;
}
string l_strCommand = "QUIT\r\n";
string l_strOutput = "";
int l_iRetval = ExecuteCommand(l_strCommand,ref l_strOutput);
/* Close socket handle here */
CloseConnection();
m_ClientSocket = null;
return 1;
}
/// <summary>
/// Creates a folder in the remote server
/// </summary>
/// <param name="l_strFolder">Name of the folder to be created</param>
/// <returns>1 if success, else 0</returns>
public int CreateFolder(string l_strFolder){
int l_iRetval = 0;
string l_strCommand = "",l_strOutput = "";
l_strCommand = "MKD " + l_strFolder + "\r\n";
/* Execute the actual command here */
l_iRetval = ExecuteCommand(l_strCommand,ref l_strOutput);
return l_iRetval;
}
/// <summary>
/// Removes a folder from the server
/// </summary>
/// <param name="l_strFolder">Name of the folder to be deleted</param>
/// <returns>1 if success, else 0</returns>
public int RemoveFolder(string l_strFolder){
int l_iRetval = 0;
string l_strCommand = "",l_strOutput = "";
l_strCommand = "RMD " + l_strFolder + "\r\n";
/* Execute the actual command here */
l_iRetval = ExecuteCommand(l_strCommand,ref l_strOutput);
return l_iRetval;
}
/// <summary>
/// Download a file from FTP server
/// </summary>
/// <param name="l_strServerFileName">Remote File full path</param>
/// <param name="l_strLocalFileName">Local File full path</param>
/// <returns>non zero value if success,else 0</returns>
public int DownLoadFile(string l_strServerFileName,string l_strLocalFileName){
/* Read 5 K at a time */
Byte[] l_bRecvData = new Byte[5120];
TcpListener l_FTPListener = null;
Socket l_ClientDataSocket = null;
bool l_bAcceptFailed = false;
/* Local file handle for stream mode */
FileStream l_fsOutFile = null;
/* File handle for Binary files */
BinaryWriter l_fbOutFile = null;
int l_iRetval = 0, l_iDataPort = 0;
int l_iBufferLimit = 5119;
try {
l_FTPListener = new TcpListener(0);
l_FTPListener.Start();
IPEndPoint pt = (IPEndPoint) l_FTPListener.LocalEndpoint;
l_iDataPort = pt.Port;
string l_strOutput = "";
string l_strPortParams = GetPortParameters(l_iDataPort);
/* Open Files here */
if ( m_chTransferType == 'A' ) {
/* Open ASCII stream */
l_fsOutFile = new FileStream(l_strLocalFileName,FileMode.Create,FileAccess.Write);
}
/* PORT command */
string l_strPortCommand = "PORT " + l_strPortParams + "\r\n";
l_iRetval = ExecuteCommand(l_strPortCommand,ref l_strOutput);
Trace.WriteLine("Port Command :" + l_iRetval + ":" + l_strOutput);
if ( l_iRetval == 0 ) {
return l_iRetval;
}
string l_strCommand = "RETR " + l_strServerFileName + "\r\n";
/* Execute the actual command here */
l_iRetval = ExecuteCommand(l_strCommand,ref l_strOutput);
if ( l_iRetval == 0 ) {
return l_iRetval;
}
/* Accept Client connection here,
* only if there is a pending connection
* */
Thread.Sleep(500);
if ( l_FTPListener.Pending()) {
l_ClientDataSocket = l_FTPListener.AcceptSocket();
}
else {
/* Else return from the download function with error */
l_bAcceptFailed = true;
m_strError = "No connection from Server. Aborting the process. Try later";
return 0;
}
l_ClientDataSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout,m_iRecvTimeOut);
l_ClientDataSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout,m_iSendTimeOut);
l_bRecvData.Initialize();
l_strOutput = "";
l_iRetval = 0;
/* Loop through and Receive all the data */
Thread.Sleep(1000);
for ( ; l_ClientDataSocket.Available > 0 ; ) {
l_bRecvData.Initialize();
l_iRetval = l_ClientDataSocket.Receive(l_bRecvData,l_iBufferLimit,0);
/* Write to Local file here */
l_fsOutFile.Write(l_bRecvData,0,l_iRetval);
l_fsOutFile.Flush();
Thread.Sleep(100);
}
if ( l_iRetval == 0 ) {
/* Connection closed by FTP Server process
* then the file transfer is complete
* */
l_iRetval = 1;
}
else if ( l_iRetval == -1 ) {
/* If Timeout occured then the FTP Server process
* didn't respond in a timely fashion
*/
l_iRetval = 0;
m_strError = "Timeout occured. FTP Server process did not respond in a timely fashion. Try increasing Receive timeout property in Configure dialog";
}
/* Close Data Connection here */
if ( l_ClientDataSocket != null ) {
l_ClientDataSocket.Shutdown(SocketShutdown.Both);
l_ClientDataSocket.Close();
l_ClientDataSocket = null;
}
/* Code to receive the response code 226 for
* RETR command from command socket
* */
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -