一个粗略实用的C#日志类(第二版卡塔尔国

作者:必威体育网页进入    发布时间:2020-03-14 10:10    浏览:122 次

[返回]

resStream.Close();

#region byte
//管理网页Byte
byte[] ResponseByte = GetByte();
#endregion

 

using System;
using System.Net;

/// </summary>

#region Html
if (ResponseByte != null & ResponseByte.Length > 0)
{
//设置编码
SetEncoding(item, result, ResponseByte);
//获得重回的HTML
result.Html = encoding.GetString(ResponseByte);
}
else
{
//未有回去任何Html代码
result.Html = string.Empty;
}
#endregion
}
/// <summary>
/// 设置编码
/// </summary>
/// <param name="item">HttpItem</param>
/// <param name="result">HttpResult</param>
/// <param name="ResponseByte">byte[]</param>
private void SetEncoding(HttpItem item, HttpResult result, byte[] ResponseByte)
{
//是或不是重临Byte类型数据
if (item.ResultType == ResultType.Byte) result.ResultByte = ResponseByte;
//从这里早先大家要无视编码了
if (encoding == null)
{
Match meta = Regex.Match(Encoding.Default.GetString(ResponseByte), "<meta[^<]*charset=([^<]*)["']", RegexOptions.IgnoreCase);
string c = string.Empty;
if (meta != null && meta.Groups.Count > 0)
{
c = meta.Groups[1].Value.ToLower().Trim();
}
if (c.Length > 2)
{
try
{
encoding = Encoding.GetEncoding(c.Replace(""", string.Empty).Replace("'", "").Replace(";", "").Replace("iso-8859-1", "gbk").Trim());
}
catch
{
if (string.IsNullOrEmpty(response.CharacterSet))
{
encoding = Encoding.UTF8;
}
else
{
encoding = Encoding.GetEncoding(response.CharacterSet);
}
}
}
else
{
if (string.IsNullOrEmpty(response.CharacterSet))
{
encoding = Encoding.UTF8;
}
else
{
encoding = Encoding.GetEncoding(response.CharacterSet);
}
}
}
}
/// <summary>
/// 提取网页Byte
/// </summary>
/// <returns></returns>
private byte[] GetByte()
{
byte[] ResponseByte = null;
MemoryStream _stream = new MemoryStream();

public static class Log
{
    private static LogManager logManager;
    static Log()
    {
        logManager = new LogManager();
    }

        /// <summary>
        /// 给FTP服务器上的文本增加内容
        /// </summary>
        /// <param name="stream">数据流(可透过安装偏移来完成从一定岗位上立刻传卡塔尔国</param>
        /// <param name="remoteFileName">FTP服务器上的公文</param>
        /// <returns>重返二个值,提醒是不是追加成功</returns>
        public bool Append(Stream stream, string remoteFileName)
        {
            bool result = false;
            if (stream != null && stream.CanRead)
            {
                //创建连接
                string url = Host.TrimEnd('/') + RemotePath + remoteFileName;
                FtpWebRequest request = CreateRequest(url, WebRequestMethods.Ftp.AppendFile);
                using (Stream rs = request.GetRequestStream())
                {
                    //上传数据
                    byte[] buffer = new byte[4096];//4K
                    int count = stream.Read(buffer, 0, buffer.Length);
                    while (count > 0)
                    {
                        rs.Write(buffer, 0, count);
                        count = stream.Read(buffer, 0, buffer.Length);
                    }
                    result = true;
                }
            }
            return result;
        }
        #endregion

/// <summary>

//GZIIP处理
if (response.ContentEncoding != null && response.ContentEncoding.Equals("gzip", StringComparison.InvariantCultureIgnoreCase))
{
//起头读取流并安装编码方式
_stream = GetMemoryStream(new GZipStream(response.GetResponseStream(), CompressionMode.Decompress));
}
else
{
//起始读取流并安装编码格局
_stream = GetMemoryStream(response.GetResponseStream());
}
//获取Byte
ResponseByte = _stream.ToArray();
_stream.Close();
return ResponseByte;
}

 第一版:贰个简短实用的C#日志类(第一版)

 

}

/// <summary>
/// 依照相传入的多少,获得相应页面数据
/// </summary>
/// <param name="item">参数类对象</param>
/// <returns>返回HttpResult类型</returns>
public HttpResult GetHtml(HttpItem item)
{
//再次来到参数
HttpResult result = new HttpResult();
try
{
//准备参数
SetRequest(item);
}
catch (Exception ex)
{
result.Cookie = string.Empty;
result.Header = null;
result.Html = ex.Message;
result.StatusDescription = "配置参数时出错:" + ex.Message;
//配置参数时出错
return result;
}
try
{
//诉求数据
using (response = (HttpWebResponse)request.GetResponse())
{
GetData(item, result);
}
}
catch (WebException ex)
{
if (ex.Response != null)
{
using (response = (HttpWebResponse)ex.Response)
{
GetData(item, result);
}
}
else
{
result.Html = ex.Message;
}
}
catch (Exception ex)
{
result.Html = ex.Message;
}
if (item.IsToLower) result.Html = result.Html.ToLower();
return result;
}
#endregion

public class LogManager
{
    private string logFileName = string.Empty;
    private string logPath = "Log";
    private string logFileExtName = "log";
    private bool writeLogTime = true;
    private bool logFileNameEndWithDate = true;
    private Encoding logFileEncoding = Encoding.UTF8;
    private object obj = new object();

        #region 上传八个文书到远端路线下
        /// <summary>
        /// 把公文上传到FTP服务器的RemotePath下
        /// </summary>
        /// <param name="localFile">本三步跳件新闻</param>
        /// <param name="remoteFileName">要保存到FTP文件服务器上的称号</param>
        public bool Upload(FileInfo localFile, string remoteFileName)
        {
            bool result = false;
            if (localFile.Exists)
            {
                string url = Host.TrimEnd('/') + RemotePath + remoteFileName;
                FtpWebRequest request = CreateRequest(url, WebRequestMethods.Ftp.UploadFile);

using System;

#region GetData

 

            return result;
        }
        #endregion

/// 再次来到提醒音讯

#region private main
/// <summary>
/// 回调验证证书难点
/// </summary>
/// <param name="sender">流对象</param>
/// <param name="certificate">证书</param>
/// <param name="chain">X509Chain</param>
/// <param name="errors">SslPolicyErrors</param>
/// <returns>bool</returns>
private bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) { return true; }
#endregion
}
/// <summary>
/// Http央浼参照他事他说加以考察类
/// </summary>
public class HttpItem
{
string _URL = string.Empty;
/// <summary>
/// 央浼U大切诺基L必需填写
/// </summary>
public string URL
{
get { return _URL; }
set { _URL = value; }
}
string _Method = "GET";
/// <summary>
/// 央浼形式默以为GET情势,当为POST情势时必须设置Postdata的值
/// </summary>
public string Method
{
get { return _Method; }
set { _Method = value; }
}
int _Timeout = 100000;
/// <summary>
/// 暗中认可央浼超时时间
/// </summary>
public int Timeout
{
get { return _Timeout; }
set { _Timeout = value; }
}
int _ReadWriteTimeout = 30000;
/// <summary>
/// 暗许写入Post数据超时间
/// </summary>
public int ReadWriteTimeout
{
get { return _ReadWriteTimeout; }
set { _ReadWriteTimeout = value; }
}
Boolean _KeepAlive = true;
/// <summary>
/// 获取或设置二个值,该值提醒是不是与 Internet 财富建构悠久性连接默认为true。
/// </summary>
public Boolean KeepAlive
{
get { return _KeepAlive; }
set { _KeepAlive = value; }
}
string _Accept = "text/html, application/xhtml+xml, */*";
/// <summary>
/// 央浼标头值 默感觉text/html, application/xhtml+xml, */*
/// </summary>
public string Accept
{
get { return _Accept; }
set { _Accept = value; }
}
string _ContentType = "text/html";
/// <summary>
/// 需要重临类型私下认可 text/html
/// </summary>
public string ContentType
{
get { return _ContentType; }
set { _ContentType = value; }
}
string _UserAgent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)";
/// <summary>
/// 顾客端访问音讯暗中同意Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0卡塔尔国
/// </summary>
public string UserAgent
{
get { return _UserAgent; }
set { _UserAgent = value; }
}
Encoding _Encoding = null;
/// <summary>
/// 重返数据编码默感到NUll,能够自动识别,经常为utf-8,gbk,gb2312
/// </summary>
public Encoding Encoding
{
get { return _Encoding; }
set { _Encoding = value; }
}
private PostDataType _PostDataType = PostDataType.String;
/// <summary>
/// Post的数据类型
/// </summary>
public PostDataType PostDataType
{
get { return _PostDataType; }
set { _PostDataType = value; }
}
string _Postdata = string.Empty;
/// <summary>
/// Post央求时要发送的字符串Post数据
/// </summary>
public string Postdata
{
get { return _Postdata; }
set { _Postdata = value; }
}
private byte[] _PostdataByte = null;
/// <summary>
/// Post央浼时要发送的Byte类型的Post数据
/// </summary>
public byte[] PostdataByte
{
get { return _PostdataByte; }
set { _PostdataByte = value; }
}
private WebProxy _WebProxy;
/// <summary>
/// 设置代理对象,不想利用IE私下认可配置就设置为Null,并且不要设置ProxyIp
/// </summary>
public WebProxy WebProxy
{
get { return _WebProxy; }
set { _WebProxy = value; }
}

    public void WriteLog(LogFile logFile, string msg)
    {
        this.WriteLog(logFile.ToString(), msg);
    }

        #region 设置是或不是允许Ssl
        private bool enableSsl = false;
        /// <summary>
        /// EnableSsl
        /// </summary>
        public bool EnableSsl
        {
            get
            {
                return enableSsl;
            }
        }
        #endregion

}

private Version _ProtocolVersion;

    public static void WriteLog(string logFile, string msg)
    {
        logManager.WriteLog(logFile, msg);
    }
}

5xx - 永远性否定的做到答复
该命令不成功,错误是永远性的。纵然顾客端重试命令,将再度现身相符的荒诞。 • 500 语法错误,命令不能够分辨。那大概满含诸如命令行太长之类的错误。
• 501 在参数中有语法错误。
• 502 未实行命令。
• 503 错误的命令系列。
• 504 未实行该参数的授命。
• 530 未登录。
• 532 存款和储蓄文件须求帐户。
• 550 未进行须求的操作。文件不可用(比如,未找到文件,未有访谈权限)。
• 551 央求的操作拾分终止:未知的页面类型。
• 552 伸手的公文操作非常终止:超过存款和储蓄分配(对于当前目录或数据集)。
• 553 未实行诉求的操作。不容许的文件名。
广阔的 FTP 状态代码及其原因
• 150 - FTP 使用多个端口:21 用于发送命令,20 用于发送数据。状态代码 150 表示服务器计划在端口 20 上张开新连接,发送一些数据。
• 226 - 命令在端口 20 上开荒数据连接以执行操作,如传输文件。该操作成功做到,数据连接已关闭。
• 230 - 客户端发送正确的密码后,显示该情况代码。它象征客商已成功登陆。
• 331 - 客商端发送客商名后,展现该景况代码。无论所提供的客商名是还是不是为系统中的有效帐户,都将显示该情形代码。
• 426 - 命令张开数据连接以实行操作,但该操作已被收回,数据连接已关闭。
• 530 - 该情状代码表示顾客不可能登录,因为客商名和密码组合无效。假设使用某些顾客帐户登入,可能键入错误的客户名或密码,也说不佳选择只同意无名访谈。假如选拔无名氏帐户登陆,IIS 的配备或然推却佚名访问。
• 550 - 命令未被推行,因为钦赐的文本不可用。比方,要 GET 的公文并不设有,或试图将文件 PUT 到你未有写入权限的目录。
*/

public string Url

#region SetRequest

    #endregion

        #region 主机
        private string host = string.Empty;
        /// <summary>
        /// 主机
        /// </summary>
        public string Host
        {
            get
            {
                return this.host ?? string.Empty;
            }
        }
        #endregion

/// <summary>

}
/// <summary>
/// Http重回参数类
/// </summary>
public class HttpResult
{
private string _Cookie;
/// <summary>
/// Http诉求再次来到的Cookie
/// </summary>
public string Cookie
{
get { return _Cookie; }
set { _Cookie = value; }
}

图片 1图片 2LogManager

        #region 使用被动方式
        private bool usePassive = true;
        /// <summary>
        /// 被动形式
        /// </summary>
        public bool UsePassive
        {
            get
            {
                return usePassive;
            }
            set
            {
                this.usePassive = value;
            }
        }
        #endregion

/// 功效:得到Internet上的U奔驰M级L页的源码

#region Public

    #region 结构函数
    public LogManager()
    {
        this.LogPath = "Log";
        this.LogFileExtName = "log";
        this.WriteLogTime = true;
        this.logFileNameEndWithDate = true;
        this.logFileEncoding = Encoding.UTF8;
    }

        #region 二进制方式
        private bool useBinary = true;
        /// <summary>
        /// 二进制格局
        /// </summary>
        public bool UseBinary
        {
            get
            {
                return useBinary;
            }
            set
            {
                this.useBinary = value;
            }
        }
        #endregion

#region 结构函数

CookieCollection cookiecollection = null;
/// <summary>
/// Cookie对象集合
/// </summary>
public CookieCollection CookieCollection
{
get { return cookiecollection; }
set { cookiecollection = value; }
}
string _Cookie = string.Empty;
/// <summary>
/// 央浼时的Cookie
/// </summary>
public string Cookie
{
get { return _Cookie; }
set { _Cookie = value; }
}
string _Referer = string.Empty;
/// <summary>
/// 来源地址,上次访问地址
/// </summary>
public string Referer
{
get { return _Referer; }
set { _Referer = value; }
}
string _CerPath = string.Empty;
/// <summary>
/// 证书相对路线
/// </summary>
public string CerPath
{
get { return _CerPath; }
set { _CerPath = value; }
}
private Boolean isToLower = false;
/// <summary>
/// 是不是设置为全文小写,默认为不转会
/// </summary>
public Boolean IsToLower
{
get { return isToLower; }
set { isToLower = value; }
}
private Boolean allowautoredirect = false;
/// <summary>
/// 协理跳转页面,查询结果将是跳转后的页面,暗中同意是不跳转
/// </summary>
public Boolean Allowautoredirect
{
get { return allowautoredirect; }
set { allowautoredirect = value; }
}
private int connectionlimit = 1024;
/// <summary>
/// 最加纳Ake拉接数
/// </summary>
public int Connectionlimit
{
get { return connectionlimit; }
set { connectionlimit = value; }
}
private string proxyusername = string.Empty;
/// <summary>
/// 代理Proxy 服务器顾客名
/// </summary>
public string ProxyUserName
{
get { return proxyusername; }
set { proxyusername = value; }
}
private string proxypwd = string.Empty;
/// <summary>
/// 代理 服务器密码
/// </summary>
public string ProxyPwd
{
get { return proxypwd; }
set { proxypwd = value; }
}
private string proxyip = string.Empty;
/// <summary>
/// 代理 服务IP ,要是要接收IE代理就安装为ieproxy
/// </summary>
public string ProxyIp
{
get { return proxyip; }
set { proxyip = value; }
}
private ResultType resulttype = ResultType.String;
/// <summary>
/// 设置再次来到类型String和Byte
/// </summary>
public ResultType ResultType
{
get { return resulttype; }
set { resulttype = value; }
}
private WebHeaderCollection header = new WebHeaderCollection();
/// <summary>
/// header对象
/// </summary>
public WebHeaderCollection Header
{
get { return header; }
set { header = value; }
}

 

 

/// 代理服务器密码

/// <summary>
/// 获取数据的并剖析的不二诀窍
/// </summary>
/// <param name="item"></param>
/// <param name="result"></param>
private void GetData(HttpItem item, HttpResult result)
{
#region base
//获取StatusCode
result.StatusCode = response.StatusCode;
//获取StatusDescription
result.StatusDescription = response.StatusDescription;
//获取Headers
result.Header = response.Headers;
//获取CookieCollection
if (response.Cookies != null) result.CookieCollection = response.Cookies;
//获取set-cookie
if (response.Headers["set-cookie"] != null) result.Cookie = response.Headers["set-cookie"];
#endregion

    public LogManager(string logPath, string logFileExtName, bool writeLogTime)
    {
        this.LogPath = logPath;
        this.LogFileExtName = logFileExtName;
        this.WriteLogTime = writeLogTime;
        this.logFileNameEndWithDate = true;
        this.logFileEncoding = Encoding.UTF8;
    }

        #region 给FTP服务器上的文书扩充内容
        /// <summary>
        /// 给FTP服务器上的文书扩充内容
        /// </summary>
        /// <param name="localFile">当半夏件</param>
        /// <param name="remoteFileName">FTP服务器上的文件</param>
        /// <returns>再次回到三个值,提醒是还是不是扩大成功</returns>
        public bool Append(FileInfo localFile, string remoteFileName)
        {
            if (localFile.Exists)
            {
                using (FileStream fs = new FileStream(localFile.FullName, FileMode.Open))
                {
                    return Append(fs, remoteFileName);
                }
            }
            throw new Exception(string.Format("本羊眼半夏件子虚乌有,文件路线:{0}", localFile.FullNameState of Qatar卡塔尔(قطر‎;
        }

public GetPageCode()

using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.IO;
using System.Text.RegularExpressions;
using System.IO.Compression;
using System.Security.Cryptography.X509Certificates;
using System.Net.Security;

    #region 属性
    /// <summary>
    /// Log 文件路线
    /// </summary>
    public string LogPath
    {
        get
        {
            if (this.logPath == null || this.logPath == string.Empty)
            {
                //Application.StartupPath
                this.logPath = AppDomain.CurrentDomain.BaseDirectory;
            }
            return this.logPath;
        }
        set
        {
            this.logPath = value;
            if (this.logPath == null || this.logPath == string.Empty)
            {
                //Application.StartupPath
                this.logPath = AppDomain.CurrentDomain.BaseDirectory;
            }
            else
            {
                try
                {
                    // 判定是或不是不是相对路线(相对路线里还或者有":")
                    if (this.logPath.IndexOf(Path.VolumeSeparatorChar) >= 0)
                    { /* 相对路线 */}
                    else
                    {
                        // 相对路线
                        this.logPath = AppDomain.CurrentDomain.BaseDirectory + this.logPath;
                    }
                    if (!Directory.Exists(this.logPath))
                        Directory.CreateDirectory(this.logPath);
                }
                catch
                {
                    this.logPath = AppDomain.CurrentDomain.BaseDirectory;
                }
                if (!this.logPath.EndsWith(@""))
                    this.logPath += @"";
            }
        }
    }

        #region 在FTP服务器上创办目录
        /// <summary>
        /// 在当前目录下创建文件夹
        /// </summary>
        /// <param name="dirName">文件夹名称</param>
        /// <returns>重回三个值,提示是或不是创立成功</returns>
        public bool MakeDirectory(string dirName)
        {
            bool result = false;
            //创设连接
            string url = Host.TrimEnd('/') + RemotePath + dirName;
            FtpWebRequest request = CreateRequest(url, WebRequestMethods.Ftp.MakeDirectory);
            using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
            {
                result = true;
            }
            return result;
        }
        #endregion

WebRequest request = WebRequest.Create(this.url);

/// <summary>
// 获取或安装用于央求的 HTTP 版本。重临结果:用于需要的 HTTP 版本。默以为System.Net.HttpVersion.Version11。
/// </summary>
public Version ProtocolVersion
{
get { return _ProtocolVersion; }
set { _ProtocolVersion = value; }
}
private Boolean _expect100continue = true;
/// <summary>
/// 获取或安装多个 System.Boolean 值,该值分明是不是利用 100-Continue 行为。假如 POST 央求须要 100-Continue 响应,则为 true;不然为 false。默许值为 true。
/// </summary>
public Boolean Expect100Continue
{
get { return _expect100continue; }
set { _expect100continue = value; }
}
private X509CertificateCollection _ClentCertificates;
/// <summary>
/// 设置509证书会集
/// </summary>
public X509CertificateCollection ClentCertificates
{
get { return _ClentCertificates; }
set { _ClentCertificates = value; }
}
private Encoding _PostEncoding;
/// <summary>
/// 设置或得到Post参数编码,私下认可的为Default编码
/// </summary>
public Encoding PostEncoding
{
get { return _PostEncoding; }
set { _PostEncoding = value; }
}
private ResultCookieType _ResultCookieType = ResultCookieType.String;
/// <summary>
/// Cookie重临类型,暗许的是只回去字符串类型
/// </summary>
public ResultCookieType ResultCookieType
{
get { return _ResultCookieType; }
set { _ResultCookieType = value; }
}

    public void WriteLog(string msg)
    {
        this.WriteLog(string.Empty, msg);
    }
    #endregion
}

        /// <summary>
        /// 创建FTP工具
        /// </summary>
        /// <param name="host">主机名称</param>
        /// <param name="userId">用户名</param>
        /// <param name="password">密码</param>
        /// <param name="port">端口</param>
        /// <param name="enableSsl">允许Ssl</param>
        /// <param name="proxy">代理</param>
        /// <param name="useBinary">允许二进制</param>
        /// <param name="usePassive">允许被动情势</param>
        public FtpClient(string host, string userId, string password, int port, IWebProxy proxy, bool enableSsl, bool useBinary, bool usePassive)
        {
            this.userId = userId;
            this.password = password;
            if (host.ToLower().StartsWith("ftp://"))
            {
                this.host = host;
            }
            else
            {
                this.host = "ftp://" + host;
            }
            this.port = port;
            this.proxy = proxy;
            this.enableSsl = enableSsl;
            this.useBinary = useBinary;
            this.usePassive = usePassive;
        }
        #endregion

if(fi.Exists)

/// <summary>
/// 为号令计划参数
/// </summary>
///<param name="item">参数列表</param>
private void SetRequest(HttpItem item)
{
// 验证证书
SetCer(item);
//设置Header参数
if (item.Header != null && item.Header.Count > 0) foreach (string key in item.Header.AllKeys)
{
request.Headers.Add(key, item.Header[key]);
}
// 设置代理
SetProxy(item);
if (item.ProtocolVersion != null) request.ProtocolVersion = item.ProtocolVersion;
request.ServicePoint.Expect100Continue = item.Expect100Continue;
//央浼方式Get大概Post
request.Method = item.Method;
request.Timeout = item.Timeout;
request.KeepAlive = item.KeepAlive;
request.ReadWriteTimeout = item.ReadWriteTimeout;
if (item.IfModifiedSince != null) request.IfModifiedSince = Convert.ToDateTime(item.IfModifiedSince);
//Accept
request.Accept = item.Accept;
//ContentType再次回到类型
request.ContentType = item.ContentType;
//UserAgent客商端的访谈类型,包罗浏览器版本和操作系统新闻
request.UserAgent = item.UserAgent;
// 编码
encoding = item.Encoding;
//设置安全凭证
request.Credentials = item.ICredentials;
//设置Cookie
SetCookie(item);
//来源地址
request.Referer = item.Referer;
//是或不是执行跳转成效
request.AllowAutoRedirect = item.Allowautoredirect;
if (item.MaximumAutomaticRedirections > 0)
{
request.MaximumAutomaticRedirections = item.MaximumAutomaticRedirections;
}
//设置Post数据
SetPostData(item);
//设置最达累斯萨拉姆接
if (item.Connectionlimit > 0) request.ServicePoint.ConnectionLimit = item.Connectionlimit;
}
/// <summary>
/// 设置证书
/// </summary>
/// <param name="item"></param>
private void SetCer(HttpItem item)
{
if (!string.IsNullOrEmpty(item.CerPath))
{
//这一句必要求写在开立连接的前面。使用回调的不二秘技开展证件验证。
ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(CheckValidationResult);
//开始化对像,并设置须要的U本田CR-VL地址
request = (HttpWebRequest)WebRequest.Create(item.URL);
SetCerList(item);
//将证件加多到央浼里
request.ClientCertificates.Add(new X509Certificate(item.CerPath));
}
else
{
//最早化对像,并安装哀告的URAV4L地址
request = (HttpWebRequest)WebRequest.Create(item.URL);
SetCerList(item);
}
}
/// <summary>
/// 设置三个证件
/// </summary>
/// <param name="item"></param>
private void SetCerList(HttpItem item)
{
if (item.ClentCertificates != null && item.ClentCertificates.Count > 0)
{
foreach (X509Certificate c in item.ClentCertificates)
{
request.ClientCertificates.Add(c);
}
}
}
/// <summary>
/// 设置Cookie
/// </summary>
/// <param name="item">Http参数</param>
private void SetCookie(HttpItem item)
{
if (!string.IsNullOrEmpty(item.Cookie)) request.Headers[HttpRequestHeader.Cookie] = item.Cookie;
//设置CookieCollection
if (item.ResultCookieType == ResultCookieType.CookieCollection)
{
request.CookieContainer = new CookieContainer();
if (item.CookieCollection != null && item.CookieCollection.Count > 0)
request.CookieContainer.Add(item.CookieCollection);
}
}
/// <summary>
/// 设置Post数据
/// </summary>
/// <param name="item">Http参数</param>
private void SetPostData(HttpItem item)
{
//验证在获得结果时是不是有传出数据
if (!request.Method.Trim().ToLower().Contains("get"))
{
if (item.PostEncoding != null)
{
postencoding = item.PostEncoding;
}
byte[] buffer = null;
//写入Byte类型
if (item.PostDataType == PostDataType.Byte && item.PostdataByte != null && item.PostdataByte.Length > 0)
{
//验证在获取结果时是或不是有传出数据
buffer = item.PostdataByte;
}//写入文件
else if (item.PostDataType == PostDataType.FilePath && !string.IsNullOrEmpty(item.Postdata))
{
StreamReader r = new StreamReader(item.Postdata, postencoding);
buffer = postencoding.GetBytes(r.ReadToEnd());
r.Close();
} //写入字符串
else if (!string.IsNullOrEmpty(item.Postdata))
{
buffer = postencoding.GetBytes(item.Postdata);
}
if (buffer != null)
{
request.ContentLength = buffer.Length;
request.GetRequestStream().Write(buffer, 0, buffer.Length);
}
}
}
/// <summary>
/// 设置代理
/// </summary>
/// <param name="item">参数对象</param>
private void SetProxy(HttpItem item)
{
bool isIeProxy = false;
if (!string.IsNullOrEmpty(item.ProxyIp))
{
isIeProxy = item.ProxyIp.ToLower().Contains("ieproxy");
}
if (!string.IsNullOrEmpty(item.ProxyIp) && !isIeProxy)
{
//设置代理服务器
if (item.ProxyIp.Contains(":"))
{
string[] plist = item.ProxyIp.Split(':');
WebProxy myProxy = new WebProxy(plist[0].Trim(), Convert.ToInt32(plist[1].Trim()));
//提出连接
myProxy.Credentials = new NetworkCredential(item.ProxyUserName, item.ProxyPwd);
//给当下号召对象
request.Proxy = myProxy;
}
else
{
WebProxy myProxy = new WebProxy(item.ProxyIp, false);
//建议连接
myProxy.Credentials = new NetworkCredential(item.ProxyUserName, item.ProxyPwd);
//给当下乞请对象
request.Proxy = myProxy;
}
}
else if (isIeProxy)
{
//设置为IE代理
}
else
{
request.Proxy = item.WebProxy;
}
}
#endregion

    /// <summary>
    /// 是不是在各种Log行后面增加当前光阴
    /// </summary>
    public bool WriteLogTime
    {
        get { return this.writeLogTime; }
        set { this.writeLogTime = value; }
    }

3xx - 自然的高级中学级答复
该命令已成功,但服务器须求越多来自客商端的音讯以实现对央浼的管理。 • 331 客户名科学,须求密码。
• 332 要求报到帐户。
• 350 央浼的公文操作正在等待进一层的新闻。

public string NoteMessage

namespace DotNet.Utilities
{
/// <summary>
/// Http连接操作辅助类
/// </summary>
public class HttpHelper
{

using System;
using System.Text;
using System.IO;

        #region 从当前目录下获得文件列表
        /// <summary>
        /// 获取当前目录下文件列表
        /// </summary>
        /// <returns></returns>
        public List<string> GetFileList()
        {
            List<string> result = new List<string>();
            //建立连接
            string url = Host.TrimEnd('/') + RemotePath;
            FtpWebRequest request = CreateRequest(url, WebRequestMethods.Ftp.ListDirectory);
            using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
            {
                StreamReader reader = new StreamReader(response.GetResponseStream(卡塔尔, System.Text.Encoding.DefaultState of Qatar;//中文文件名
                string line = reader.ReadLine();
                while (line != null)
                {
                    result.Add(line);
                    line = reader.ReadLine();
                }
            }
            return result;
        }
        #endregion

private string proxyPassword=null;

private ICredentials _ICredentials = CredentialCache.DefaultCredentials;
/// <summary>
/// 获取或安装央求的身份验证消息。
/// </summary>
public ICredentials ICredentials
{
get { return _ICredentials; }
set { _ICredentials = value; }
}
/// <summary>
/// 设置央求将随行的重定向的最大数据
/// </summary>
private int _MaximumAutomaticRedirections;

    /// <summary>
    /// 日志文件的字符编码
    /// </summary>
    public Encoding LogFileEncoding
    {
        get { return logFileEncoding; }
        set { logFileEncoding = value; }
    }
    #endregion

        #region 获取FTP服务器上的这几天路径
        /// <summary>
        /// 获取FTP服务器上的当下路径
        /// </summary>
        public string CurrentDirectory
        {
            get
            {
                string result = string.Empty;
                string url = Host.TrimEnd('/') + RemotePath;
                FtpWebRequest request = CreateRequest(url, WebRequestMethods.Ftp.PrintWorkingDirectory);
                using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
                {
                    string temp = response.StatusDescription;
                    int start = temp.IndexOf('"') + 1;
                    int end = temp.LastIndexOf('"');
                    if (end >= start)
                    {
                        result = temp.Substring(start, end - start);
                    }
                }
                return result;

/// </summary>

/// <summary>
/// 4.0以下.net版本取数据运用
/// </summary>
/// <param name="streamResponse">流</param>
private MemoryStream GetMemoryStream(Stream streamResponse)
{
MemoryStream _stream = new MemoryStream();
int Length = 256;
Byte[] buffer = new Byte[Length];
int bytesRead = streamResponse.Read(buffer, 0, Length);
while (bytesRead > 0)
{
_stream.Write(buffer, 0, bytesRead);
bytesRead = streamResponse.Read(buffer, 0, Length);
}
return _stream;
}
#endregion

    public static void WriteLog(LogFile logFile, string msg)
    {
        logManager.WriteLog(logFile, msg);
    }

4xx - 眨眼间态否定的实现答复
该命令不成功,但错误是权且的。借使顾客端重试命令,也许会推行成功。 • 421 服务不可用,正在关闭调整连接。假设服务鲜明它必需关闭,将向别的命令发送这一遍复。
• 425 不只怕开荒数据连接。
• 426 Connection closed; transfer aborted.
• 450 未进行央求的文件操作。文件不可用(譬喻,文件繁忙)。
• 451 乞请的操作极其终止:正在管理地方错误。
• 452 未实践央浼的操作。系统存款和储蓄空间远远不够。

/// 输出的字符串

private DateTime? _IfModifiedSince = null;
/// <summary>
/// 获取和装置IfModifiedSince,默觉伏贴明日子和时间
/// </summary>
public DateTime? IfModifiedSince
{
get { return _IfModifiedSince; }
set { _IfModifiedSince = value; }
}

    /// <summary>
    /// Log 文件扩充名
    /// </summary>
    public string LogFileExtName
    {
        get { return this.logFileExtName; }
        set { this.logFileExtName = value; }
    }

/*
FTP全状态码查询辞典
 
1xx - 自然的开始回答
这几个情形代码提示一项操作已经成功开始,但客商端希望在继续操作新命令前获得另二个答应。 • 110 重新开动标志答复。
• 120 服务已就绪,在 nnn 秒钟后起先。
• 125 数据连接已开荒,正在伊始传输。
• 150 文件状态不荒谬,酌量展开数据连接。

}

#region 预订义方变量
//暗许的编码
private Encoding encoding = Encoding.Default;
//Post数据编码
private Encoding postencoding = Encoding.Default;
//HttpWebRequest对象用来倡导呼吁
private HttpWebRequest request = null;
//获取影响流的数码对象
private HttpWebResponse response = null;
#endregion

public enum LogFile
{
    Trace,
    Error,
    SQL,
    SQLError
}

        #region 从FTP服务器上删除目录
        /// <summary>
        /// 删除文件夹
        /// </summary>
        /// <param name="dirName">文件夹名称</param>
        /// <returns>重返叁个值,提醒是不是删除成功</returns>
        public bool DeleteDirectory(string dirName)
        {
            bool result = false;
            //建设构造连接
            string url = Host.TrimEnd('/') + RemotePath + dirName;
            FtpWebRequest request = CreateRequest(url, WebRequestMethods.Ftp.RemoveDirectory);
            using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
            {
                result = true;
            }
            return result;
        }
        #endregion

/// </summary>

private CookieCollection _CookieCollection;
/// <summary>
/// 库克ie对象群集
/// </summary>
public CookieCollection CookieCollection
{
get { return _CookieCollection; }
set { _CookieCollection = value; }
}
private string _html = string.Empty;
/// <summary>
/// 再次来到的String类型数据 独有ResultType.String时才再次来到数据,此外情状为空
/// </summary>
public string Html
{
get { return _html; }
set { _html = value; }
}
private byte[] _ResultByte;
/// <summary>
/// 再次回到的Byte数组 独有ResultType.Byte时才再次回到数据,别的景况为空
/// </summary>
public byte[] ResultByte
{
get { return _ResultByte; }
set { _ResultByte = value; }
}
private WebHeaderCollection _Header;
/// <summary>
/// header对象
/// </summary>
public WebHeaderCollection Header
{
get { return _Header; }
set { _Header = value; }
}
private string _StatusDescription;
/// <summary>
/// 重临状态说明
/// </summary>
public string StatusDescription
{
get { return _StatusDescription; }
set { _StatusDescription = value; }
}
private HttpStatusCode _StatusCode;
/// <summary>
/// 再次回到状态码,默认为OK
/// </summary>
public HttpStatusCode StatusCode
{
get { return _StatusCode; }
set { _StatusCode = value; }
}
}
/// <summary>
/// 再次来到类型
/// </summary>
public enum ResultType
{
/// <summary>
/// 代表只回去字符串 只有Html有数量
/// </summary>
String,
/// <summary>
/// 代表回去字符串和字节流 ResultByte和Html都有数量重临
/// </summary>
Byte
}
/// <summary>
/// Post的数据格式默许为string
/// </summary>
public enum PostDataType
{
/// <summary>
/// 字符串类型,这个时候编码Encoding可不设置
/// </summary>
String,
/// <summary>
/// Byte类型,必要安装PostdataByte参数的值编码Encoding可设置为空
/// </summary>
Byte,
/// <summary>
/// 传文件,Postdata必需安装为文件的相对路线,必得设置Encoding的值
/// </summary>
FilePath
}
/// <summary>
/// Cookie重临类型
/// </summary>
public enum ResultCookieType
{
/// <summary>
/// 只回去字符串类型的Cookie
/// </summary>
String,
/// <summary>
/// CookieCollection格式的Cookie集左券不常间也回到String类型的cookie
/// </summary>
CookieCollection
}
}

    /// <summary>
    /// 日志文件名是还是不是带日期
    /// </summary>
    public bool LogFileNameEndWithDate
    {
        get { return logFileNameEndWithDate; }
        set { logFileNameEndWithDate = value; }
    }

2xx - 自然的完毕答复
一项操作已经打响做到。客商端能够试行新命令。 • 200 命令鲜明。
• 202 未实践命令,站点上的指令过多。
• 211 系统状态,或连串支持答复。
• 212 目录状态。
• 213 文件状态。
• 214 帮忙音讯。
• 215 NAME 系统项目,在那之中,NAME 是 Assigned Numbers 文书档案中所列的正经系统名称。
• 220 服务就绪,能够实行新客商的倡议。
• 221 服务关闭调整连接。假使方便,请注销。
• 225 数据连接展开,未有开展中的传输。
• 226 关闭数据连接。央求的文本操作已成功(举个例子,传输文件或遗弃文件)。
• 227 进入被动方式 (h1,h2,h3,h4,p1,p2State of Qatar。
• 230 客商已报到,继续张开。
• 250 央求的文书操作不易,已形成。
• 257 已创建“PATHNAME”。

/// </summary>

public int MaximumAutomaticRedirections
{
get { return _MaximumAutomaticRedirections; }
set { _MaximumAutomaticRedirections = value; }
}

    #region 公有方法
    public void WriteLog(string logFile, string msg)
    {
        lock (obj)
        {
            try
            {
                string dateString = string.Empty;
                if (this.logFileNameEndWithDate || logFile.Length == 0)
                {
                    dateString = DateTime.Now.ToString("yyyyMMdd");
                }
                logFileName = string.Format("{0}{1}{2}.{3}",
                                            this.LogPath,
                                            logFile,
                                            dateString,
                                            this.logFileExtName);
                using (StreamWriter sw = new StreamWriter(logFileName, true, logFileEncoding))
                {
                    if (writeLogTime)
                    {
                        sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss: ") + msg);
                    }
                    else
                    {
                        sw.WriteLine(msg);
                    }
                }
            }
            catch
            { }
        }
    }

                //上传数据
                using (Stream rs = request.GetRequestStream())
                using (FileStream fs = localFile.OpenRead())
                {
                    byte[] buffer = new byte[4096];//4K
                    int count = fs.Read(buffer, 0, buffer.Length);
                    while (count > 0)
                    {
                        rs.Write(buffer, 0, count);
                        count = fs.Read(buffer, 0, buffer.Length);
                    }
                    fs.Close();
                    result = true;
                }
                return result;
            }
            throw new Exception(string.Format("当麻芋果件官样文章,文件路线:{0}", localFile.FullName卡塔尔(قطر‎卡塔尔国;
        }
        #endregion

sw.Close();

        #region 从FTP服务器上下载文件
        /// <summary>
        /// 从当前目录下下载文件
        /// <para>
        /// 如若当三步跳件存在,则从地点文件结束的职位上马下载.
        /// </para>
        /// </summary>
        /// <param name="serverName">服务器上的文件名称</param>
        /// <param name="localName">当羊眼半夏件名称</param>
        /// <returns>重返叁个值,提醒是或不是下载成功</returns>
        public bool Download(string serverName, string localName)
        {
            bool result = false;
            using (FileStream fs = new FileStream(localName, FileMode.OpenOrCreate卡塔尔(قطر‎卡塔尔国 //创建或张开当羊眼半夏件
            {
                //创立连接
                string url = Host.TrimEnd('/') + RemotePath + serverName;
                FtpWebRequest request = CreateRequest(url, WebRequestMethods.Ftp.DownloadFile);
                request.ContentOffset = fs.Length;
                using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
                {
                    fs.Position = fs.Length;
                    byte[] buffer = new byte[4096];//4K
                    int count = response.GetResponseStream().Read(buffer, 0, buffer.Length);
                    while (count > 0)
                    {
                        fs.Write(buffer, 0, count);
                        count = response.GetResponseStream().Read(buffer, 0, buffer.Length);
                    }
                    response.GetResponseStream().Close();
                }
                result = true;
            }
            return result;
        }
        #endregion

Stream resStream = response.GetResponseStream();

            return result;
        }
        #endregion

        #region 重命名FTP服务器上的文书
        /// <summary>
        /// 文件更名
        /// </summary>
        /// <param name="oldFileName">原版的书文件名</param>
        /// <param name="newFileName">新文件名</param>
        /// <returns>重临三个值,提醒更名是还是不是中标</returns>
        public bool Rename(string oldFileName, string newFileName)
        {
            bool result = false;
            //建设布局连接
            string url = Host.TrimEnd('/') + RemotePath + oldFileName;
            FtpWebRequest request = CreateRequest(url, WebRequestMethods.Ftp.Rename);
            request.RenameTo = newFileName;
            using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
            {
                result = true;
            }
            return result;
        }
        #endregion

}

//FTP开源封装的类

}

namespace FTP
{
    /// <summary>
    /// FTP客商端操作类
    /// </summary>
    public class FtpClient
    {
        #region 布局函数
        /// <summary>
        /// 创建FTP工具
        /// <para>
        /// 暗中同意不行使SSL,使用二进制传输方式,使用被动形式
        /// </para>
        /// </summary>
        /// <param name="host">主机名称</param>
        /// <param name="userId">用户名</param>
        /// <param name="password">密码</param>
        public FtpClient(string host, string userId, string password)
            : this(host, userId, password, 21, null, false, true, true)
        {
        }

gpc.OutFilePath=filePath;//设置输出文件路径的地点,要是不安装,则赶回字符串

        #region 从FTP服务器上剔除文件
        /// <summary>
        /// 删除FTP服务器上的文本
        /// </summary>
        /// <param name="fileName">文件名称</param>
        /// <returns>重临二个值,提醒是还是不是删除成功</returns>
        public bool DeleteFile(string fileName)
        {
            bool result = false;
            //创立连接
            string url = Host.TrimEnd('/') + RemotePath + fileName;
            FtpWebRequest request = CreateRequest(url, WebRequestMethods.Ftp.DeleteFile);
            using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
            {
                result = true;
            }

/// </summary>

        #region 代理
        IWebProxy proxy = null;
        /// <summary>
        /// 代理
        /// </summary>
        public IWebProxy Proxy
        {
            get
            {
                return this.proxy;
            }
            set
            {
                this.proxy = value;
            }
        }
        #endregion

}

 //操作轨范

{

             //////////////////////////////////////////////////////////////////////////
            //下载服务器上的某一天的excel文件,然后开展NPOI操作
            FtpClient fcc = new FtpClient("127.0.0.1","text","123"卡塔尔(قطر‎;//输入主机IP,客商名,密码
            fcc.Download("02" + DateTime.Now.ToString("yyyyMMdd") + ".xls",@"c:2.xls"卡塔尔;//将ftp服务器上的文本02二零一三0213.xls的文本下载到当麻芋果建上
            using(FileStream fs=File.OpenRead(@"c:2.xls"))
            {
                HSSFWorkbook wb = new HSSFWorkbook(fs);
                HSSFSheet sheet = wb.GetSheetAt(0State of Qatar;//获取第一张表
                Console.Write(sheet.LastRowNum.ToString());
               
            }
            Console.WriteLine("nOK");

}

            }
        }
        #endregion

#endregion

 

/// 是不是利用代理服务器标记

        #region 从FTP服务器上赢得文件大小
        /// <summary>
        /// 获取文件大小
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public long GetFileSize(string fileName)
        {
            long result = 0;
            //组建连接
            string url = Host.TrimEnd('/') + RemotePath + fileName;
            FtpWebRequest request = CreateRequest(url, WebRequestMethods.Ftp.GetFileSize);
            using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
            {
                result = response.ContentLength;
            }

/// </summary>

        #region 从FTP服务器上收获文件和文书夹列表
        /// <summary>
        /// 获取详细列表
        /// </summary>
        /// <returns></returns>
        public List<string> GetFileDetails()
        {
            List<string> result = new List<string>();
            //营造连接
            string url = Host.TrimEnd('/') + RemotePath;
            FtpWebRequest request = CreateRequest(url, WebRequestMethods.Ftp.ListDirectoryDetails);
            using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
            {
                StreamReader reader = new StreamReader(response.GetResponseStream(State of Qatar, System.Text.Encoding.DefaultState of Qatar;//粤语文件名
                string line = reader.ReadLine();
                while (line != null)
                {
                    result.Add(line);
                    line = reader.ReadLine();
                }
            }
            return result;
        }
        #endregion

/// <summary>

        #region 密码
        private string password = string.Empty;
        /// <summary>
        /// 密码
        /// </summary>
        public string Password
        {
            get
            {
                return this.password;
            }
        }
        #endregion

FileInfo fi = new FileInfo(this.outFilePath);

        #region 检查当前路径上是还是不是留存某些文件
        /// <summary>
        /// 检查文件是还是不是存在
        /// </summary>
        /// <param name="fileName">要反省的文本名</param>
        /// <returns>再次来到叁个值,提醒要检查的文本是还是不是存在</returns>
        public bool CheckFileExist(string fileName)
        {
            bool result = false;
            if (fileName != null && fileName.Trim().Length > 0)
            {
                fileName = fileName.Trim();
                List<string> files = GetFileList();
                if (files != null && files.Count > 0)
                {
                    foreach (string file in files)
                    {
                        if (file.ToLower() == fileName.ToLower())
                        {
                            result = true;
                            break;
                        }
                    }
                }
            }
            return result;
        }
        #endregion

set{outFilePath=value;}

namespace FTP
{
    class Program
    {
        static void Main(string[] args)
        {
            //WebClient 只可以上传下载,别的都干不了
            WebClient wc = new WebClient();
            //设定客户名和密码
            wc.Credentials = new NetworkCredential("test","123");
            wc.DownloadFile("", "c:/wawa.text");
            wc.UploadFile("", "c:/cust.xls");
            //自定义封装的类操作FTP
            FtpClient fc = new FtpClient("127.0.0.1","Text","123");
            fc.Download("write.xls", "c:/haha.slx");
            Console.Read();
        }
    }
}

sr.Close();

        #region 端口
        private int port = 21;
        /// <summary>
        /// 端口
        /// </summary>
        public int Port
        {
            get
            {
                return port;
            }
            set
            {
                this.port = value;
            }
        }
        #endregion

gpc.ProxyAddress="

        #region 远端路线
        private string remotePath = "/";
        /// <summary>
        /// 远端路线
        /// <para>
        ///     重临FTP服务器上的当前路径(能够是 / 或 /a/../ 的款式卡塔尔
        /// </para>
        /// </summary>
        public string RemotePath
        {
            get
            {
                return remotePath;
            }
            set
            {
                string result = "/";
                if (!string.IsNullOrEmpty(value) && value != "/")
                {
                    result = "/" + value.TrimStart('/').TrimEnd('/') + "/";
                }
                this.remotePath = result;
            }
        }
        #endregion

/// 代理服务器顾客名

    }
}

{

        #region 创立七个FTP连接
        /// <summary>
        /// 创设四个FTP央浼
        /// </summary>
        /// <param name="url">须要地址</param>
        /// <param name="method">乞求方法</param>
        /// <returns>FTP请求</returns>
        private FtpWebRequest CreateRequest(string url, string method)
        {
            //营造连接
            FtpWebRequest request = (FtpWebRequest)WebRequest.Create(url);
            request.Credentials = new NetworkCredential(this.userId, this.password);
            request.Proxy = this.proxy;
            request.KeepAlive = false;//命令施行落成之后关闭连接
            request.UseBinary = useBinary;
            request.UsePassive = usePassive;
            request.EnableSsl = enableSsl;
            request.Method = method;
            return request;
        }
        #endregion

get{return proxyState;}

using System;
using System.Collections.Generic;
using System.Net;
using System.IO;

{

        #region 登入客户名
        private string userId = string.Empty;
        /// <summary>
        /// 登入顾客名
        /// </summary>
        public string UserId
        {
            get
            {
                return this.userId;
            }
        }
        #endregion

StreamWriter sw = new StreamWriter(this.outFilePath,true,Encoding.Default);

}

/// </summary>

catch

set{proxyState=value;}

using System.Web;

/// 输出文件路线

string tempCode=gpc.OutString;//重回的字符串

/// <summary>

/// </summary>

搜索