C\#FTP 클 라 이언 트 를 실현 하 는 작은 예
생각:
관련 지식 포인트:
효과 도 는 다음 과 같다
왼쪽:하위 디 렉 터 리 에 폴 더 를 더 블 클릭 하고 도구 모음 단 추 를 누 르 면'상위 디 렉 터 리'를 되 돌려 줍 니 다.파일 은 오른쪽 단 추 를 누 르 면 작 동 합 니 다.
오른쪽:폴 더 는 앞+번 호 를 누 르 면 펼 쳐 집 니 다.파일 은 오른쪽 단 추 를 눌 러 업로드 합 니 다.
핵심 코드 는 다음 과 같다.
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
}
}
FTP 서버 와 클 라 이언 트 설명도이상 은 C\#FTP 클 라 이언 트 를 실현 하 는 작은 사례 의 상세 한 내용 입 니 다.C\#FTP 클 라 이언 트 를 실현 하 는 데 관 한 자 료 는 저희 의 다른 관련 글 을 주목 하 십시오!
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
C#Task를 사용하여 비동기식 작업을 수행하는 방법라인이 완성된 후에 이 라인을 다시 시작할 수 없습니다.반대로 조인(Join)만 결합할 수 있습니다 (프로세스가 현재 라인을 막습니다). 임무는 조합할 수 있는 것이다. 연장을 사용하여 그것들을 한데 연결시키는 것이...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.