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;
using FluentFTP;
namespace DemoFtp
{
public class FtpHelper
{
#region 屬性與構造函數
/// <summary>
/// IP地址
/// </summary>
public string IpAddr { get; set; }
/// <summary>
/// 相對路徑
/// </summary>
public string RelatePath { get; set; }
/// <summary>
/// 端口號
/// </summary>
public int Port { get; set; }
/// <summary>
/// 用戶名
/// </summary>
public string UserName { get; set; }
/// <summary>
/// 密碼
/// </summary>
public string Password { get; set; }
public FtpHelper()
{
}
public FtpHelper(string ipAddr, int port, string userName, string password, string relatePath)
{
this.IpAddr = ipAddr;
this.Port = port;
this.UserName = userName;
this.Password = password;
this.RelatePath = relatePath;
}
#endregion
#region 方法
public FtpListItem[] ListDir() {
FtpListItem[] lists;
using (var ftpClient = new FtpClient(this.IpAddr, this.UserName, this.Password, this.Port))
{
ftpClient.Connect();
ftpClient.SetWorkingDirectory(this.RelatePath);
lists = ftpClient.GetListing();
}
return lists;
}
public void UpLoad(string dir, string file, out bool isOk)
{
isOk = false;
FileInfo fi = new FileInfo(file);
using (FileStream fs = fi.OpenRead())
{
//long length = fs.Length;
using (var ftpClient = new FtpClient(this.IpAddr, this.UserName, this.Password, this.Port))
{
ftpClient.Connect();
ftpClient.SetWorkingDirectory(this.RelatePath);
string remotePath = dir + "/" + Path.GetFileName(file);
var ftpRemodeExistsMode = file.EndsWith(".txt") ? FtpRemoteExists.Overwrite : FtpRemoteExists.Skip;
FtpStatus status = ftpClient.UploadStream(fs, remotePath, ftpRemodeExistsMode, true);
isOk = status == FtpStatus.Success;
}
}
}
/// <summary>
/// 上傳多個文件
/// </summary>
/// <param name="files"></param>
/// <param name="isOk"></param>
public void UpLoad(string dir, string[] files, out bool isOk)
{
isOk = false;
if (CheckDirIsExists(dir))
{
foreach (var file in files)
{
UpLoad(dir, file, out isOk);
}
}
}
private bool CheckDirIsExists(string dir)
{
bool flag = false;
using (var ftpClient = new FtpClient(this.IpAddr, this.UserName, this.Password, this.Port))
{
ftpClient.Connect();
ftpClient.SetWorkingDirectory(this.RelatePath);
flag = ftpClient.DirectoryExists(dir);
if (!flag)
{
flag = ftpClient.createDirectory(dir);
}
}
return flag;
}
/// <summary>
/// 下載ftp
/// </summary>
/// <param name="localAddress"></param>
/// <param name="remoteAddress"></param>
/// <returns></returns>
public bool DownloadFile(string localAddress, string remoteAddress)
{
using (var ftpClient = new FtpClient(this.IpAddr, this.UserName, this.Password, this.Port))
{
ftpClient.SetWorkingDirectory("/");
ftpClient.Connect();
if (ftpClient.DownloadFile(localAddress, remoteAddress) == FtpStatus.Success)
{
return true;
}
return false;
}
}
#endregion
}
}