⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 ftpclient.cs

📁 ftp浏览器
💻 CS
📖 第 1 页 / 共 4 页
字号:
				Byte[] l_bRecvCommData = new Byte[512];
				l_bRecvCommData.Initialize();
				string l_strTemp = "";

				l_strOutput = "";
				int l_iRetval1 = 1;
				if ( m_strError.Length > 0 ) {
					l_strTemp = m_strError;
				}

				for ( ; m_ClientSocket.Available > 0 ; ) {
					l_iRetval1 = m_ClientSocket.Receive(l_bRecvCommData,511,0);
					l_strTemp = Encoding.ASCII.GetString(l_bRecvCommData,0,l_iRetval1);
					l_strOutput += l_strTemp;
				}

				/*	Parse the output string */
				if ( l_strOutput.Length > 3 ) {
					l_iRetval1 = ParseResponseCode("RETR",l_strOutput.Substring(0,3));
				}
				if ( l_iRetval1 == 0 ) {
					if ( l_strTemp.Length > 0 ) {
						m_strError = l_strTemp;
					}
					l_iRetval = 0;
				}
				return l_iRetval;
			}
			catch ( Exception e ) {
				m_strError = e.Message;
				return 0;
			}
			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;
				}
				if ( l_fsOutFile != null ) {
					l_fsOutFile.Close();
				}
				if ( l_fbOutFile != null ) {
					l_fbOutFile.Close();
				}

				/*	If Accept() failed, then receive the data from
				 *	command connection and ignore it.
				 * */
				if ( l_bAcceptFailed == true ) {
					Byte[] l_bRecvCommData = new Byte[512];
					l_bRecvCommData.Initialize();

					/*	Get all data and do not do anything with the data.
					 *	This is just to clear the command connection data
					 */
					for ( ; m_ClientSocket.Available > 0 ; ) {
						m_ClientSocket.Receive(l_bRecvCommData,511,0);
					}
				}
			}	/*	End of finally */
		}	/*	End of download file */


		/// <summary>
		/// Uploads file to FTP Server
		/// </summary>
		/// <param name="l_strLocalFile">Local file full path</param>
		/// <param name="l_strRemoteFile">Remote file full path</param>
		/// <returns>non zero value if success, else 0</returns>
		public int UploadFile(string l_strLocalFile,string l_strRemoteFile){

			int l_iRetval = 0,l_iDataPort = 0;

			/* Send 5k at a time */
			Byte[] l_bData = new Byte[5120];

			TcpListener l_FTPListener = null;
			Socket l_ClientDataSocket = null;
			bool l_bAcceptFailed = false;
			
			/*	Local file handle for stream mode */
			FileStream l_fsInFile = null;

			try {

				l_FTPListener = new TcpListener(0);
				l_FTPListener.Start();
				IPEndPoint pt = (IPEndPoint) l_FTPListener.LocalEndpoint;
				l_iDataPort = pt.Port;

				string l_strOutput = "",l_strCommand = "";
				string l_strPortParams = GetPortParameters(l_iDataPort);

				m_strError = "";

				/*	Open Files here */
				if ( m_chTransferType == 'A' ) {
					/*	Open ASCII stream */
					l_fsInFile = new FileStream(l_strLocalFile,FileMode.Open,FileAccess.Read);
				}

				/*	PORT command */
				string l_strPortCommand = "PORT " + l_strPortParams + "\r\n";
				l_iRetval = ExecuteCommand(l_strPortCommand,ref l_strOutput);
				if ( l_iRetval == 0 ) {
					return l_iRetval;
				}

				l_strCommand = "STOR " + l_strRemoteFile + "\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 upload function with error */
					l_bAcceptFailed = true;
					m_strError = "No connection from Server. Aborting the process. Try later";
					return 0;
				}

				/* Set Socket options */
				l_ClientDataSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout,m_iRecvTimeOut);
				l_ClientDataSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout,m_iSendTimeOut);
				
				l_bData.Initialize();
				l_strOutput = "";
				l_iRetval = 0;

				/*	Loop through and Receive all the data */
				Thread.Sleep(1000);
				for ( ; (l_iRetval = l_fsInFile.Read(l_bData,0,5119)) != 0 ; ) {

					/* Write to socket here and check for return value */
					l_iRetval = l_ClientDataSocket.Send(l_bData,l_iRetval + 1,0);
					if ( l_iRetval == 0 ) {
						/*	If Connection closed by FTP server,
						 *	then close the connection
						 */
						l_iRetval = 0;
						m_strError = "Connection closed by FTP Server. Aborting the upload process.";
						return l_iRetval;
					}
					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 Send timeout property in Configure dialog";
						return l_iRetval;
					}
					l_bData.Initialize();
				}	/* end of for() */

				if ( l_iRetval == 0 ) {
					/*	End of File is reached and 
					 *	the file transfer is complete
					 * */
					l_iRetval = 1;
				}

				/*	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 
				 *	STOR command from command socket
				 * */
				Byte[] l_bRecvCommData = new Byte[512];
				l_bRecvCommData.Initialize();
				string l_strTemp = "";

				l_strOutput = "";
				int l_iRetval1 = 1;
				if ( m_strError.Length > 0 ) {
					l_strTemp = m_strError;
				}

				for ( ; m_ClientSocket.Available > 0 ; ) {
					l_iRetval1 = m_ClientSocket.Receive(l_bRecvCommData,511,0);
					l_strTemp = Encoding.ASCII.GetString(l_bRecvCommData,0,l_iRetval1);
					l_strOutput += l_strTemp;
				}

				/*	Parse the output string */
				if ( l_strOutput.Length > 3 ) {
					l_iRetval1 = ParseResponseCode("STOR",l_strOutput.Substring(0,3));
				}
				if ( l_iRetval1 == 0 ) {
					if ( l_strTemp.Length > 0 ) {
						m_strError = l_strTemp;
					}
					l_iRetval = 0;
				}
				return l_iRetval ;
			}
			catch ( Exception e) {
				m_strError = e.Message;
				l_iRetval = 0;
			}
			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;
				}
				if ( l_fsInFile != null ) {
					l_fsInFile.Close();
				}

				/*	If Accept() failed, then receive the data from
				 *	command connection and ignore it.
				 * */
				if ( l_bAcceptFailed == true ) {
					Byte[] l_bRecvCommData = new Byte[512];
					l_bRecvCommData.Initialize();

					/*	Get all data and do not do anything with the data.
					 *	This is just to clear the command connection data
					 */
					for ( ; m_ClientSocket.Available > 0 ; ) {
						m_ClientSocket.Receive(l_bRecvCommData,511,0);
					}
				}
			}
			return l_iRetval;
		}

		/// <summary>
		/// Remove a file from the remote server
		/// </summary>
		/// <param name="l_strFile">File to be removed</param>
		/// <returns>1 if success, else 0</returns>
		public int RemoveFile(string l_strFile){
			int l_iRetval = 0;
			string l_strCommand = "",l_strOutput = "";
			l_strCommand = "DELE " + l_strFile + "\r\n";
			
			/*	Execute the actual command here */
			l_iRetval = ExecuteCommand(l_strCommand,ref l_strOutput);
			return l_iRetval;
		}

		/// <summary>
		/// Changes the current working folder
		/// </summary>
		/// <param name="l_strDirectory">Folder name to be set as current working folder</param>
		/// <returns>1 if success, else 0</returns>
		public int ChangeWorkingFolder(string l_strDirectory){
			/*	CWD command */
			string l_strCommand = "";
			string l_strOutput = "";
			int l_iRetval = 0;

			m_strError = "";

			/*	USER command */
			l_strCommand = "CWD " + l_strDirectory + "\r\n";
			l_iRetval = ExecuteCommand(l_strCommand,ref l_strOutput);
			if ( l_iRetval == 0 ) {
				return l_iRetval;
			}

			m_strCurrentWorkingDir = l_strDirectory;
			return 1;
		}

		/// <summary>
		/// To Parse the output of LIST command from Windows FTP services
		/// </summary>
		/// <param name="l_arrFiles">Input string read from socket connection</param>
		/// <returns>DataTable if success, else null</returns>
		private DataTable ParseStringArrayForWindows(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)));

			string l_strcurFile = "";
			char[] l_arrchSep = new char[2];
			l_arrchSep[0] = ' ';
			l_arrchSep[1] = '\0';
			string[] l_strarrFields = new string[5];

			foreach(object obj in l_arrFiles) {
				l_strcurFile = (string) obj;
				l_strcurFile.Trim();
				
				if (l_strcurFile == null || l_strcurFile.Length == 0 ) {
					break;
				}

				l_strarrFields = SplitStringForWindows(l_strcurFile);
				if ( l_strarrFields.Length == 1 || l_strarrFields.Length <= 0 ) {
					/*	If the element is empty, do not attempt to parse it */
					continue;
				}

				/*	Each field is now in l_strarrFields */
				DataRow l_drNew = l_dtFileList.NewRow();
				/*	Each field is now in l_strarrFields */
				if ( GetFileInfoForWindows(l_strarrFields,ref l_drNew) == 1 ){
					if ( l_drNew != null ) {
						l_dtFileList.Rows.Add(l_drNew);
					}
				}
			}
			return l_dtFileList;
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="l_strInString"></param>
		/// <returns></returns>
		private string[] SplitStringForWindows(string l_strInString){
			string[] l_strarrOut = new string[5];
			string l_strTemp = "";
			char[] l_arrchSep = new char[2];
			l_arrchSep[0] = ' ';
			l_arrchSep[1] = '\0';
			int l_iFieldCount = 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] == ' ' ) {
					if ( l_iFieldCount <= 1 ) {
						l_strarrOut[l_iFieldCount] = l_strTemp;
						l_iFieldCount++;
						l_strTemp = "";
						if ( l_strInString[l_iCount + 1] == ' ' ) {
							for ( l_iCount++ ;  l_strInString[l_iCount] == ' '; l_iCount++ ) ;
							/*	Postion the counter back to previous character	*/
							l_iCount--;
						}
					}
					else if ( l_iFieldCount == 2 ) {
						/*	Check for first digit here 
						 * if '<' then it is a directory
						 * else it is a file
						 * */
						if ( l_strTemp[0] == '<' ) {
							/*	Directory Flag	*/
							l_strarrOut[l_iFieldCount] = "D";
							l_iFieldCount++;

							/*	size of directory is not known	*/
							l_strarrOut[l_iFieldCount] = "0";
							l_iFieldCount++;
							/*	Skip the rest of characters */
							for ( l_iCount++ ;  l_strInString[l_iCount] != ' '; l_iCount++ ) ;
						}
						else {
							/*	Normal File	*/
							l_strarrOut[l_iFieldCount] = "N";
							l_iFieldCount++;
							l_strarrOut[l_iFieldCount] = l_strTemp;
							l_iFieldCount++;
						}
					}
				}
				else {
					if ( l_iFieldCount == 4 ) {
						/*	File name */
						l_strTemp = "";
						for ( ; l_iCount < l_strInString.Length ; l_iCount++ ){
							l_strTemp += l_strInString[l_iCount];
						}
						/*	remove \r\n character */
						l_strTemp = l_strTemp.Substring(0,l_strTemp.Length - 1);
						l_strarrOut[l_iFieldCount] = l_strTemp;
					}
					else {
						l_strTemp += l_strInString[l_iCount];
					}
				}
			}
			return l_strarrOut;
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="l_strarrFields"></param>
		/// <param name="l_drNew"></param>
		/// <returns></returns>
		private int GetFileInfoForWindows(string[] l_strarrFields,ref DataRow l_drNew){

			string l_strField = "";
			string l_strFileName = "" ,l_strFilePath = "" ,l_strDateCreated = "";
			string l_strTimeCreated = "";
			int l_iFileType = 0,l_iFileSize = 0;
			int l_iCount = 0;

			foreach(object obj in l_strarrFields) {
				l_strField = (string) obj;
				if (l_strField == null ) {
					break;
				}
				switch( l_iCount) {
					case 0:		/*	Date */
						l_strDateCreated = l_strField;
						break;
					case 1 :	/*	Time */
						l_strTimeCreated = l_strField;
						break;
					case 2 :	/*	File Type  N - normal file, D - directory	*/
						if ( l_strField.Equals("N") ) {
							l_iFileType = 1;
						}
						else if ( l_strField.Equals("D") ) {
							l_iFileType = 2;
						}
						break;
					case 3 :	/*	File size in bytes */
						try {
							l_iFileSize = int.Parse(l_strField);
						}
						catch ( FormatException e ) {
							l_iFileSize = 0;
						}
						break;
					case 4 :	/*	Name of the file */
						l_strFileName = l_strField;
						break;
				}	/*	End of switch statement */
				l_iCount++;
			}	/*	End of for */

			/* If current or parent directory */
			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;
			return 1;
		}

		/// <summary>
		/// Closes the socket connection
		/// </summary>
		private void CloseConnection(){
			if ( m_ClientSocket != null ) {
				m_ClientSocket.Shutdown(SocketShutdown.Both);
				m_ClientSocket.Close();
				m_ClientSocket = null;
			}
			return;
		}

	}
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -