FTPClientHelper 보조 클래스 는 파일 업로드,디 렉 터 리 조작,다운로드 등 을 실현 합 니 다.
32927 단어 FTPClientHelper보조 류
이 문 서 는 ftp 파일 의 업로드 다운로드 등 명령 을 수행 하기 위해 Socket 통신 방식 을 사용 합 니 다.
1.기본 소개
최근 의 프로젝트 는 클 라 이언 트 의 프로그램 이기 때문에 클 라 이언 트 의 이미지 파일[컷 팅]-[포장]-[ftp 업로드]를 해 야 합 니 다.지금 은 마지막 단계 가 남 았 습 니 다.이런 작은 기능 을 천천히 실현 하 는 것 이 큰 기능 입 니 다.그래서 하나의 업 무 는 아주 작 게 나 누 어야 잘 볼 수 있 습 니 다.이 프로젝트 에 실제 어떤 지식 이 필요 한 지 ftp 업로드 명령 을 소개 합 니 다.
ftp 명령 참조 링크:https://www.jb51.net/article/12199.htm
ftp 는 작은 파일 업로드 에 적합 합 니 다.
대역 폭 에 대한 요구 가 비교적 높다.
서버 보안 도 고려 해 야 합 니 다.
명령 은 익숙해 져 야 지,그렇지 않 으 면 비교적 어렵다.
2.실제 항목
파일 업로드
파일 다운로드
파일 삭제
폴 더 만 들 기
폴 더 이름 바 꾸 기
폴 더 삭제
디 렉 터 리 변경
폴 더 의 파일 목록 가 져 오기
등등
2.1 사진 업로드 와 다운로드
몇 가지 방법 을 썼 는데 보통 가장 많이 사용 하 는 것 은 Put 입 니 다.구체 적 으로 복사 소스 코드 를 다운로드 하여 실전 을 진행 할 수 있 습 니 다.
2.2 디 렉 터 리 생 성 및 삭제
이 방법 은 오늘 마침 써 서 잠시 고생 하고 나 서 야 해결 되 었 다.
3.호출 코드 참조
이 도움말 클래스 는 정적 인 것 이 아니 기 때문에 예화 가 필요 합 니 다.
string userName = "xxx";
string password = "xxx";
var ftp = new FTPClientHelper("xxx", ".", userName, password, 1021);
다음은 자주 사용 하 는 방법 을 호출 하면 됩 니 다.계 정,비밀번호,서버 의 IP 주 소 는 모두 제 가'xxx'로 대 체 했 기 때문에 여러분 이 직접 고 쳐 야 합 니 다.그리고 ftp 기본 포트 번 호 는 1021 입 니 다.변동 이 있 으 면 스스로 고 쳐 야 합 니 다.4.FTPClientHelper 다운로드
//-------------------------------------------------------------------------------------
// All Rights Reserved , Copyright (C) 2015 , ZTO , Ltd .
//-------------------------------------------------------------------------------------
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
namespace ZTO.PicTest.Utilities
{
/// <summary>
/// FTP
///
///
///
/// 2016-4-4 :1.0 YangHengLian , , 。
///
/// :1.0
///
/// <author>
/// <name>YangHengLian</name>
/// <date>2016-4-4</date>
/// </author>
/// </summary>
public class FTPClientHelper
{
public static object Obj = new object();
#region
/// <summary>
///
/// </summary>
public FTPClientHelper()
{
RemoteHost = "";
_strRemotePath = "";
_strRemoteUser = "";
_strRemotePass = "";
_strRemotePort = 21;
_bConnected = false;
}
/// <summary>
///
/// </summary>
public FTPClientHelper(string remoteHost, string remotePath, string remoteUser, string remotePass, int remotePort)
{
// Ip
RemoteHost = remoteHost;
// , , .
_strRemotePath = remotePath;
//
_strRemoteUser = remoteUser;
//
_strRemotePass = remotePass;
// ftp
_strRemotePort = remotePort;
Connect();
}
#endregion
#region
private int _strRemotePort;
private Boolean _bConnected;
private string _strRemotePass;
private string _strRemoteUser;
private string _strRemotePath;
/// <summary>
/// ( )
/// </summary>
private string _strMsg;
/// <summary>
/// ( )
/// </summary>
private string _strReply;
/// <summary>
///
/// </summary>
private int _iReplyCode;
/// <summary>
/// socket
/// </summary>
private Socket _socketControl;
/// <summary>
///
/// </summary>
private TransferType _trType;
/// <summary>
///
/// </summary>
private const int BlockSize = 512;
/// <summary>
///
/// </summary>
readonly Encoding _ascii = Encoding.ASCII;
/// <summary>
///
/// </summary>
readonly Byte[] _buffer = new Byte[BlockSize];
#endregion
#region
/// <summary>
/// FTP IP
/// </summary>
public string RemoteHost { get; set; }
/// <summary>
/// FTP
/// </summary>
public int RemotePort
{
get
{
return _strRemotePort;
}
set
{
_strRemotePort = value;
}
}
/// <summary>
///
/// </summary>
public string RemotePath
{
get
{
return _strRemotePath;
}
set
{
_strRemotePath = value;
}
}
/// <summary>
///
/// </summary>
public string RemoteUser
{
set
{
_strRemoteUser = value;
}
}
/// <summary>
///
/// </summary>
public string RemotePass
{
set
{
_strRemotePass = value;
}
}
/// <summary>
///
/// </summary>
public bool Connected
{
get
{
return _bConnected;
}
}
#endregion
#region
/// <summary>
///
/// </summary>
public void Connect()
{
lock (Obj)
{
_socketControl = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
var ep = new IPEndPoint(IPAddress.Parse(RemoteHost), _strRemotePort);
try
{
_socketControl.Connect(ep);
}
catch (Exception)
{
throw new IOException(" ftp ");
}
}
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);
}
/// <summary>
///
/// </summary>
public void DisConnect()
{
if (_socketControl != null)
{
SendCommand("QUIT");
}
CloseSocketConnect();
}
#endregion
#region
/// <summary>
/// : 、ASCII
/// </summary>
public enum TransferType { Binary, ASCII };
/// <summary>
///
/// </summary>
/// <param name="ttType"> </param>
public void SetTransferType(TransferType ttType)
{
SendCommand(ttType == TransferType.Binary ? "TYPE I" : "TYPE A");
if (_iReplyCode != 200)
{
throw new IOException(_strReply.Substring(4));
}
_trType = ttType;
}
/// <summary>
///
/// </summary>
/// <returns> </returns>
public TransferType GetTransferType()
{
return _trType;
}
#endregion
#region
/// <summary>
///
/// </summary>
/// <param name="strMask"> </param>
public string[] Dir(string strMask)
{
if (!_bConnected)
{
Connect();
}
Socket socketData = CreateDataSocket();
SendCommand("NLST " + strMask);
if (!(_iReplyCode == 150 || _iReplyCode == 125 || _iReplyCode == 226))
{
throw new IOException(_strReply.Substring(4));
}
_strMsg = "";
Thread.Sleep(2000);
while (true)
{
int iBytes = socketData.Receive(_buffer, _buffer.Length, 0);
_strMsg += _ascii.GetString(_buffer, 0, iBytes);
if (iBytes < _buffer.Length)
{
break;
}
}
char[] seperator = { '
' };
string[] strsFileList = _strMsg.Split(seperator);
socketData.Close(); // socket
if (_iReplyCode != 226)
{
ReadReply();
if (_iReplyCode != 226)
{
throw new IOException(_strReply.Substring(4));
}
}
return strsFileList;
}
public void NewPutByGuid(string strFileName, string strGuid)
{
if (!_bConnected)
{
Connect();
}
string str = strFileName.Substring(0, strFileName.LastIndexOf("\\", StringComparison.Ordinal));
string strTypeName = strFileName.Substring(strFileName.LastIndexOf(".", StringComparison.Ordinal));
strGuid = str + "\\" + strGuid;
Socket socketData = CreateDataSocket();
SendCommand("STOR " + Path.GetFileName(strGuid));
if (!(_iReplyCode == 125 || _iReplyCode == 150))
{
throw new IOException(_strReply.Substring(4));
}
var input = new FileStream(strGuid, FileMode.Open);
input.Flush();
int iBytes;
while ((iBytes = input.Read(_buffer, 0, _buffer.Length)) > 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));
}
}
}
/// <summary>
///
/// </summary>
/// <param name="strFileName"> </param>
/// <returns> </returns>
public long GetFileSize(string strFileName)
{
if (!_bConnected)
{
Connect();
}
SendCommand("SIZE " + Path.GetFileName(strFileName));
long lSize;
if (_iReplyCode == 213)
{
lSize = Int64.Parse(_strReply.Substring(4));
}
else
{
throw new IOException(_strReply.Substring(4));
}
return lSize;
}
/// <summary>
///
/// </summary>
/// <param name="strFileName"> </param>
/// <returns> </returns>
public string GetFileInfo(string strFileName)
{
if (!_bConnected)
{
Connect();
}
Socket socketData = CreateDataSocket();
SendCommand("LIST " + strFileName);
if (!(_iReplyCode == 150 || _iReplyCode == 125
|| _iReplyCode == 226 || _iReplyCode == 250))
{
throw new IOException(_strReply.Substring(4));
}
byte[] b = new byte[512];
MemoryStream ms = new MemoryStream();
while (true)
{
int iBytes = socketData.Receive(b, b.Length, 0);
ms.Write(b, 0, iBytes);
if (iBytes <= 0)
{
break;
}
}
byte[] bt = ms.GetBuffer();
string strResult = Encoding.ASCII.GetString(bt);
ms.Close();
return strResult;
}
/// <summary>
///
/// </summary>
/// <param name="strFileName"> </param>
public void Delete(string strFileName)
{
if (!_bConnected)
{
Connect();
}
SendCommand("DELE " + strFileName);
if (_iReplyCode != 250)
{
throw new IOException(_strReply.Substring(4));
}
}
/// <summary>
/// ( , )
/// </summary>
/// <param name="strOldFileName"> </param>
/// <param name="strNewFileName"> </param>
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
/// <summary>
///
/// </summary>
/// <param name="strFileNameMask"> </param>
/// <param name="strFolder"> ( \ )</param>
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);
}
}
}
/// <summary>
///
/// </summary>
/// <param name="strRemoteFileName"> </param>
/// <param name="strFolder"> ( \ )</param>
/// <param name="strLocalFileName"> </param>
public void Get(string strRemoteFileName, string strFolder, string strLocalFileName)
{
Socket socketData = CreateDataSocket();
try
{
if (!_bConnected)
{
Connect();
}
SetTransferType(TransferType.Binary);
if (strLocalFileName.Equals(""))
{
strLocalFileName = strRemoteFileName;
}
SendCommand("RETR " + strRemoteFileName);
if (!(_iReplyCode == 150 || _iReplyCode == 125 || _iReplyCode == 226 || _iReplyCode == 250))
{
throw new IOException(_strReply.Substring(4));
}
var output = new FileStream(strFolder + "\\" + strLocalFileName, FileMode.Create);
while (true)
{
int iBytes = socketData.Receive(_buffer, _buffer.Length, 0);
output.Write(_buffer, 0, iBytes);
if (iBytes <= 0)
{
break;
}
}
output.Close();
if (socketData.Connected)
{
socketData.Close();
}
if (!(_iReplyCode == 226 || _iReplyCode == 250))
{
ReadReply();
if (!(_iReplyCode == 226 || _iReplyCode == 250))
{
throw new IOException(_strReply.Substring(4));
}
}
}
catch
{
socketData.Close();
_socketControl.Close();
_bConnected = false;
_socketControl = null;
}
}
/// <summary>
///
/// </summary>
/// <param name="strRemoteFileName"> </param>
/// <param name="strFolder"> ( \ )</param>
/// <param name="strLocalFileName"> </param>
public void GetNoBinary(string strRemoteFileName, string strFolder, string strLocalFileName)
{
if (!_bConnected)
{
Connect();
}
if (strLocalFileName.Equals(""))
{
strLocalFileName = strRemoteFileName;
}
Socket socketData = CreateDataSocket();
SendCommand("RETR " + strRemoteFileName);
if (!(_iReplyCode == 150 || _iReplyCode == 125 || _iReplyCode == 226 || _iReplyCode == 250))
{
throw new IOException(_strReply.Substring(4));
}
var output = new FileStream(strFolder + "\\" + strLocalFileName, FileMode.Create);
while (true)
{
int iBytes = socketData.Receive(_buffer, _buffer.Length, 0);
output.Write(_buffer, 0, iBytes);
if (iBytes <= 0)
{
break;
}
}
output.Close();
if (socketData.Connected)
{
socketData.Close();
}
if (!(_iReplyCode == 226 || _iReplyCode == 250))
{
ReadReply();
if (!(_iReplyCode == 226 || _iReplyCode == 250))
{
throw new IOException(_strReply.Substring(4));
}
}
}
/// <summary>
///
/// </summary>
/// <param name="strFolder"> ( \ )</param>
/// <param name="strFileNameMask"> ( * ?)</param>
public void Put(string strFolder, string strFileNameMask)
{
string[] strFiles = Directory.GetFiles(strFolder, strFileNameMask);
foreach (string strFile in strFiles)
{
Put(strFile);
}
}
/// <summary>
///
/// </summary>
/// <param name="strFileName"> </param>
public void Put(string strFileName)
{
if (!_bConnected)
{
Connect();
}
Socket socketData = CreateDataSocket();
if (Path.GetExtension(strFileName) == "")
SendCommand("STOR " + Path.GetFileNameWithoutExtension(strFileName));
else
SendCommand("STOR " + Path.GetFileName(strFileName));
if (!(_iReplyCode == 125 || _iReplyCode == 150))
{
throw new IOException(_strReply.Substring(4));
}
var input = new FileStream(strFileName, FileMode.Open);
int iBytes;
while ((iBytes = input.Read(_buffer, 0, _buffer.Length)) > 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));
}
}
}
/// <summary>
///
/// </summary>
/// <param name="strFileName"> </param>
///
/// <param name="strGuid"> </param>
public void PutByGuid(string strFileName, string strGuid)
{
if (!_bConnected)
{
Connect();
}
string str = strFileName.Substring(0, strFileName.LastIndexOf("\\", StringComparison.Ordinal));
string strTypeName = strFileName.Substring(strFileName.LastIndexOf(".", System.StringComparison.Ordinal));
strGuid = str + "\\" + strGuid;
File.Copy(strFileName, strGuid);
File.SetAttributes(strGuid, FileAttributes.Normal);
Socket socketData = CreateDataSocket();
SendCommand("STOR " + Path.GetFileName(strGuid));
if (!(_iReplyCode == 125 || _iReplyCode == 150))
{
throw new IOException(_strReply.Substring(4));
}
var input = new FileStream(strGuid, FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read);
int iBytes = 0;
while ((iBytes = input.Read(_buffer, 0, _buffer.Length)) > 0)
{
socketData.Send(_buffer, iBytes, 0);
}
input.Close();
File.Delete(strGuid);
if (socketData.Connected)
{
socketData.Close();
}
if (!(_iReplyCode == 226 || _iReplyCode == 250))
{
ReadReply();
if (!(_iReplyCode == 226 || _iReplyCode == 250))
{
throw new IOException(_strReply.Substring(4));
}
}
}
#endregion
#region
/// <summary>
///
/// </summary>
/// <param name="strDirName"> </param>
public void MkDir(string strDirName)
{
if (!_bConnected)
{
Connect();
}
SendCommand("MKD " + strDirName);
if (_iReplyCode != 257)
{
throw new IOException(_strReply.Substring(4));
}
}
/// <summary>
///
/// </summary>
/// <param name="strDirName"> </param>
public void RmDir(string strDirName)
{
if (!_bConnected)
{
Connect();
}
SendCommand("RMD " + strDirName);
if (_iReplyCode != 250)
{
throw new IOException(_strReply.Substring(4));
}
}
/// <summary>
///
/// </summary>
/// <param name="strDirName"> </param>
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
/// <summary>
/// strReply strMsg, iReplyCode
/// </summary>
private void ReadReply()
{
_strMsg = "";
_strReply = ReadLine();
_iReplyCode = Int32.Parse(_strReply.Substring(0, 3));
}
/// <summary>
/// socket
/// </summary>
/// <returns> socket</returns>
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 <= 6; i++)
{
char ch = Char.Parse(ipData.Substring(i, 1));
if (Char.IsDigit(ch))
buf += ch;
else if (ch != ',')
{
throw new IOException("Malformed PASV strReply: " + _strReply);
}
if (ch == ',' || i + 1 == len)
{
try
{
parts[partCount++] = Int32.Parse(buf);
buf = "";
}
catch (Exception)
{
throw new IOException("Malformed PASV strReply: " + _strReply);
}
}
}
string ipAddress = parts[0] + "." + parts[1] + "." + parts[2] + "." + parts[3];
int port = (parts[4] << 8) + parts[5];
var s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
var ep = new IPEndPoint(IPAddress.Parse(ipAddress), port);
try
{
s.Connect(ep);
}
catch (Exception)
{
throw new IOException(" ftp ");
}
return s;
}
/// <summary>
/// socket ( )
/// </summary>
private void CloseSocketConnect()
{
lock (Obj)
{
if (_socketControl != null)
{
_socketControl.Close();
_socketControl = null;
}
_bConnected = false;
}
}
/// <summary>
/// Socket
/// </summary>
/// <returns> </returns>
private string ReadLine()
{
lock (Obj)
{
while (true)
{
int iBytes = _socketControl.Receive(_buffer, _buffer.Length, 0);
_strMsg += _ascii.GetString(_buffer, 0, iBytes);
if (iBytes < _buffer.Length)
{
break;
}
}
}
char[] seperator = { '
' };
string[] mess = _strMsg.Split(seperator);
if (_strMsg.Length > 2)
{
_strMsg = mess[mess.Length - 2];
}
else
{
_strMsg = mess[0];
}
if (!_strMsg.Substring(3, 1).Equals(" ")) // ( 220 , , )
{
return ReadLine();
}
return _strMsg;
}
/// <summary>
///
/// </summary>
/// <param name="strCommand"> </param>
public void SendCommand(String strCommand)
{
lock (Obj)
{
Byte[] cmdBytes = Encoding.ASCII.GetBytes((strCommand + "\r
").ToCharArray());
_socketControl.Send(cmdBytes, cmdBytes.Length, 0);
Thread.Sleep(100);
ReadReply();
}
}
#endregion
}
}
5.FTP 에서 자주 사용 하 는 명령
#region System.dll, v4.0.0.0
// C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0\System.dll
#endregion
using System;
namespace System.Net
{
// :
// System.Net.WebRequestMethods.Ftp、System.Net.WebRequestMethods.File System.Net.WebRequestMethods.Http
// 。
public static class WebRequestMethods
{
// :
// FILE 。 。
public static class File
{
// :
// FILE GET 。
public const string DownloadFile = "GET";
//
// :
// FILE PUT 。
public const string UploadFile = "PUT";
}
// :
// FTP FTP 。 。
public static class Ftp
{
// :
// FTP FTP APPE 。
public const string AppendFile = "APPE";
//
// :
// FTP FTP DELE 。
public const string DeleteFile = "DELE";
//
// :
// FTP FTP RETR 。
public const string DownloadFile = "RETR";
//
// :
// FTP FTP MDTM 。
public const string GetDateTimestamp = "MDTM";
//
// :
// FTP FTP SIZE 。
public const string GetFileSize = "SIZE";
//
// :
// FTP FTP NLIST 。
public const string ListDirectory = "NLST";
//
// :
// FTP FTP LIST 。
public const string ListDirectoryDetails = "LIST";
//
// :
// FTP FTP MKD 。
public const string MakeDirectory = "MKD";
//
// :
// FTP PWD 。
public const string PrintWorkingDirectory = "PWD";
//
// :
// FTP RMD 。
public const string RemoveDirectory = "RMD";
//
// :
// FTP RENAME 。
public const string Rename = "RENAME";
//
// :
// FTP FTP STOR 。
public const string UploadFile = "STOR";
//
// :
// FTP FTP STOU 。
public const string UploadFileWithUniqueName = "STOU";
}
// :
// HTTP HTTP 。
public static class Http
{
// :
// HTTP CONNECT , , SSL 。
public const string Connect = "CONNECT";
//
// :
// HTTP GET 。
public const string Get = "GET";
//
// :
// HTTP HEAD 。 ,HEAD GET 。
public const string Head = "HEAD";
//
// :
// HTTP MKCOL , URI( ) , 。
public const string MkCol = "MKCOL";
//
// :
// HTTP POST , URI。
public const string Post = "POST";
//
// :
// HTTP PUT , URI 。
public const string Put = "PUT";
}
}
}
이상 이 바로 본문의 전체 내용 입 니 다.여러분 께 참고 가 될 수 있 기 를 바 랍 니 다.여러분 들 도 저 희 를 많이 응원 해 주시 기 바 랍 니 다.