using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.IO;
using System.Text.RegularExpressions;
using System.Configuration;
namespace BLL
{
public class FtpSection : ConfigurationSection
{
public override bool IsReadOnly()
{
return true;
}
[ConfigurationProperty("host", IsRequired = true)]
public string Host
{
get { return this["host"] as string; }
}
[ConfigurationProperty("user", IsRequired = true)]
//[RegexStringValidator(可以在这里用正则验证配置文件中的值是否正确)]
public string User
{
get { return this["user"] as string; }
}
[ConfigurationProperty("pwd", IsRequired = true)]
public string Password
{
get { return this["pwd"] as string; }
}
[ConfigurationProperty("port", IsRequired = false, DefaultValue = 25)]
[IntegerValidator(MaxValue = 65535, MinValue = 1)]
public int Port
{
get { return (int)this["port"]; }
}
}
public class FTPHelper
{
#region 字段
string ftpURI;
string ftpUserID;
string ftpServerIP;
string ftpPassword;
string ftpRemotePath;
#endregion
/// <summary>
/// 连接FTP服务器
/// </summary>
/// <param name="FtpServerIP">FTP连接地址</param>
/// <param name="FtpRemotePath">指定FTP连接成功后的当前目录, 如果不指定即默认为根目录</param>
/// <param name="FtpUserID">用户名</param>
/// <param name="FtpPassword">密码</param>
public FTPHelper(string FtpServerIP, string FtpRemotePath, string FtpUserID, string FtpPassword)
{
ftpServerIP = FtpServerIP;
ftpRemotePath = FtpRemotePath;
ftpUserID = FtpUserID;
ftpPassword = FtpPassword;
ftpURI = "ftp://" + ftpServerIP + "/" + ftpRemotePath + "/";
ftpURI.Replace("\\", "/");
}
/// <summary>
/// 重设URL
/// </summary>
/// <param name="FtpServerIP"></param>
/// <param name="FtpRemotePath"></param>
/// <returns></returns>
public FTPHelper SetftpUrl(string ftpServerIP, string ftpRemotePath)
{
ftpURI = "ftp://" + ftpServerIP + "/" + ftpRemotePath + "/";
return this;
}
/// <summary>
/// 重设账密
/// </summary>
/// <param name="FtpUserID"></param>
/// <param name="FtpPassword"></param>
/// <returns></returns>
public FTPHelper SetUserAndPwd(string FtpUserID, string FtpPassword)
{
ftpUserID = FtpUserID;
ftpPassword = FtpPassword;
return this;
}
public string GetCurrentURL
{
get
{
return ftpURI;
}
}
/// <summary>
/// 上传
/// </summary>
public void Upload(string localfilename,string removefilename)
{
FileInfo fileInf = new FileInfo(localfilename);
FtpWebRequest reqFTP;
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI+ removefilename));
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
reqFTP.KeepAlive = false;
reqFTP.UseBinar