C\#FTP 클 라 이언 트 구현 사례

본 고 는 C\#FTP 클 라 이언 트 를 실현 하 는 작은 예 로 주로 업로드,다운로드,삭제 등 기능 을 실현 하여 학습 공유 에 사용 하도록 한다.
생각:
FTP 사이트 의 디 렉 터 리 정 보 를 읽 고 해당 하 는 파일 과 폴 더 를 보 여 줍 니 다.
디 렉 터 리 를 더 블 클릭 하면 하위 디 렉 터 리 를 표시 하고 파일 이 라면 오른쪽 단 추 를 누 르 면 다운로드 와 삭제 작업 을 합 니 다.
로 컬 컴퓨터 의 디 렉 터 리 를 읽 고 트 리 구조 로 보 여 주 며 로 컬 파일 을 선택 하고 오른쪽 단 추 를 누 르 면 업로드 작업 을 합 니 다.
관련 지식 포인트:
FtpWebRequest[파일 전송 프로 토 콜(FTP)클 라 이언 트 구현]/FtpWebResponse[파일 전송 프로 토 콜(FTP)서버 가 요청 에 대한 응답 봉인]Ftp 의 작업 은 주로 두 가지 종류 에 집중 되 어 있 습 니 다.
FlowLayoutPanel  【흐름 레이아웃 패 널]내용 을 수평 또는 수직 방향 으로 동적 으로 배출 하 는 패 널 을 표시 합 니 다.
ContextMenuStrip[단축 메뉴]는 주로 오른쪽 클릭 메뉴 에 사 용 됩 니 다.
자원 파일:Resources 는 그림 과 다른 자원 을 저장 하 는 데 사 용 됩 니 다.
효과 도 는 다음 과 같다
왼쪽:하위 디 렉 터 리 에 폴 더 를 더 블 클릭 하고 도구 모음 단 추 를 누 르 면'상위 디 렉 터 리'를 되 돌려 줍 니 다.파일 은 오른쪽 단 추 를 누 르 면 작 동 합 니 다.
오른쪽:폴 더 는 앞+번 호 를 누 르 면 펼 쳐 집 니 다.파일 은 오른쪽 단 추 를 눌 러 업로드 합 니 다.

핵심 코드 는 다음 과 같다.

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace FtpClient
{
  public class FtpHelper
  {
    #region        

    /// <summary>
    /// IP  
    /// </summary>
    public string IpAddr { get; set; }

    /// <summary>
    ///     
    /// </summary>
    public string RelatePath { get; set; }

    /// <summary>
    ///    
    /// </summary>
    public string Port { get; set; }

    /// <summary>
    ///    
    /// </summary>
    public string UserName { get; set; }

    /// <summary>
    ///   
    /// </summary>
    public string Password { get; set; }

    

    public FtpHelper() {

    }

    public FtpHelper(string ipAddr, string port, string userName, string password) {
      this.IpAddr = ipAddr;
      this.Port = port;
      this.UserName = userName;
      this.Password = password;
    }

    #endregion

    #region   


    /// <summary>
    ///     
    /// </summary>
    /// <param name="filePath"></param>
    /// <param name="isOk"></param>
    public void DownLoad(string filePath, out bool isOk) {
      string method = WebRequestMethods.Ftp.DownloadFile;
      var statusCode = FtpStatusCode.DataAlreadyOpen;
      FtpWebResponse response = callFtp(method);
      ReadByBytes(filePath, response, statusCode, out isOk);
    }

    public void UpLoad(string file,out bool isOk)
    {
      isOk = false;
      FileInfo fi = new FileInfo(file);
      FileStream fs = fi.OpenRead();
      long length = fs.Length;
      string uri = string.Format("ftp://{0}:{1}{2}", this.IpAddr, this.Port, this.RelatePath);
      FtpWebRequest request = (FtpWebRequest)WebRequest.Create(uri);
      request.Credentials = new NetworkCredential(UserName, Password);
      request.Method = WebRequestMethods.Ftp.UploadFile;
      request.UseBinary = true;
      request.ContentLength = length;
      request.Timeout = 10 * 1000;
      try
      {
        Stream stream = request.GetRequestStream();

        int BufferLength = 2048; //2K  
        byte[] b = new byte[BufferLength];
        int i;
        while ((i = fs.Read(b, 0, BufferLength)) > 0)
        {
          stream.Write(b, 0, i);
        }
        stream.Close();
        stream.Dispose();
        isOk = true;
      }
      catch (Exception ex)
      {
        Console.WriteLine(ex.ToString());
      }
      finally {
        if (request != null)
        {
          request.Abort();
          request = null;
        }
      }
    }

    /// <summary>
    ///     
    /// </summary>
    /// <param name="isOk"></param>
    /// <returns></returns>
    public string[] DeleteFile(out bool isOk) {
      string method = WebRequestMethods.Ftp.DeleteFile;
      var statusCode = FtpStatusCode.FileActionOK;
      FtpWebResponse response = callFtp(method);
      return ReadByLine(response, statusCode, out isOk);
    }

    /// <summary>
    ///     
    /// </summary>
    public string[] ListDirectory(out bool isOk)
    {
      string method = WebRequestMethods.Ftp.ListDirectoryDetails;
      var statusCode = FtpStatusCode.DataAlreadyOpen;
      FtpWebResponse response= callFtp(method);
      return ReadByLine(response, statusCode, out isOk);
    }

    /// <summary>
    ///       
    /// </summary>
    public void SetPrePath()
    {
      string relatePath = this.RelatePath;
      if (string.IsNullOrEmpty(relatePath) || relatePath.LastIndexOf("/") == 0 )
      {
        relatePath = "";
      }
      else {
        relatePath = relatePath.Substring(0, relatePath.LastIndexOf("/"));
      }
      this.RelatePath = relatePath;
    }

    #endregion

    #region     

    /// <summary>
    ///   Ftp,     Ftp     
    /// </summary>
    /// <param name="method">   Ftp   </param>
    /// <returns></returns>
    private FtpWebResponse callFtp(string method)
    {
      string uri = string.Format("ftp://{0}:{1}{2}", this.IpAddr, this.Port, this.RelatePath);
      FtpWebRequest request; request = (FtpWebRequest)FtpWebRequest.Create(uri);
      request.UseBinary = true;
      request.UsePassive = true;
      request.Credentials = new NetworkCredential(UserName, Password);
      request.KeepAlive = false;
      request.Method = method;
      FtpWebResponse response = (FtpWebResponse)request.GetResponse();
      return response;
    }

    /// <summary>
    ///     
    /// </summary>
    /// <param name="response"></param>
    /// <param name="statusCode"></param>
    /// <param name="isOk"></param>
    /// <returns></returns>
    private string[] ReadByLine(FtpWebResponse response, FtpStatusCode statusCode,out bool isOk) {
      List<string> lstAccpet = new List<string>();
      int i = 0;
      while (true)
      {
        if (response.StatusCode == statusCode)
        {
          using (StreamReader sr = new StreamReader(response.GetResponseStream()))
          {
            string line = sr.ReadLine();
            while (!string.IsNullOrEmpty(line))
            {
              lstAccpet.Add(line);
              line = sr.ReadLine();
            }
          }
          isOk = true;
          break;
        }
        i++;
        if (i > 10)
        {
          isOk = false;
          break;
        }
        Thread.Sleep(200);
      }
      response.Close();
      return lstAccpet.ToArray();
    }

    private void ReadByBytes(string filePath,FtpWebResponse response, FtpStatusCode statusCode, out bool isOk)
    {
      isOk = false;
      int i = 0;
      while (true)

      {
        if (response.StatusCode == statusCode)
        {
          long length = response.ContentLength;
          int bufferSize = 2048;
          int readCount;
          byte[] buffer = new byte[bufferSize];
          using (FileStream outputStream = new FileStream(filePath, FileMode.Create))
          {

            using (Stream ftpStream = response.GetResponseStream())
            {
              readCount = ftpStream.Read(buffer, 0, bufferSize);
              while (readCount > 0)
              {
                outputStream.Write(buffer, 0, readCount);
                readCount = ftpStream.Read(buffer, 0, bufferSize);
              }
            }
          }
          break;
        }
        i++;
        if (i > 10)
        {
          isOk = false;
          break;
        }
        Thread.Sleep(200);
      }
      response.Close();
    }
    #endregion
  }

  /// <summary>
  /// Ftp      
  /// </summary>
  public enum FtpContentType
  {
    undefined = 0,
    file = 1,
    folder = 2
  }
}
소스 코드 링크 는 다음 과 같다.
이상 이 바로 본 고의 모든 내용 입 니 다.여러분 의 학습 에 도움 이 되 고 저 희 를 많이 응원 해 주 셨 으 면 좋 겠 습 니 다.

좋은 웹페이지 즐겨찾기