C#帮助类库整理

C#帮助类库整理

1.日志记录帮助类库

根据Log4net封装:

 public class LogHelper
    {
        static LogHelper()
        {
             //通过Nuget添加Log4net的引用
            XmlConfigurator.Configure(new Uri(AppDomain.CurrentDomain.BaseDirectory+@"ConfigFiles/log4net.cfg.xml"));
            ILog log = LogManager.GetLogger(typeof(LogHelper));
            log.Info("系统初始化Logger模块");
        }

        private ILog logger = null;

        public LogHelper(Type type)
        {
            logger = LogManager.GetLogger(type);
        }

        public void Error(string msg="出現異常",Exception ex=null)
        {
            Console.WriteLine(msg);
            logger.Error(msg,ex);
        }

        public void Warn(string msg)
        {
            Console.WriteLine(msg);
            logger.Warn(msg);
        }

        public void Info(string msg)
        {
            Console.WriteLine(msg);
            logger.Info(msg);
        }

        public void Debug(string msg)
        {
            Console.WriteLine(msg);
            logger.Debug(msg);
        }

    }

<log4net>
  <!-- Define some output appenders -->
  <appender name="rollingAppender" type="log4net.Appender.RollingFileAppender">
    <file value="log\log.txt" />

    <!--追加日志内容-->
    <appendToFile value="true" />

    <!--防止多线程时不能写Log,官方说线程非安全-->
    <lockingModel type="log4net.Appender.FileAppender+MinimalLock" />

    <!--可以为:Once|Size|Date|Composite-->
    <!--Composite为Size和Date的组合-->
    <rollingStyle value="Composite" />

    <!--当备份文件时,为文件名加的后缀-->
    <datePattern value="yyyyMMdd.TXT" />

    <!--日志最大个数,都是最新的-->
    <!--rollingStyle节点为Size时,只能有value个日志-->
    <!--rollingStyle节点为Composite时,每天有value个日志-->
    <maxSizeRollBackups value="20" />

    <!--可用的单位:KB|MB|GB-->
    <maximumFileSize value="3MB" />

    <!--置为true,当前最新日志文件名永远为file节中的名字-->
    <staticLogFileName value="true" />

    <!--输出级别在INFO和ERROR之间的日志-->
    <filter type="log4net.Filter.LevelRangeFilter">
      <param name="LevelMin" value="INFO" />
      <param name="LevelMax" value="FATAL" />
    </filter>

    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%date [%thread] %-5level %logger - %message%newline"/>
    </layout>
  </appender>

  <!-- levels: OFF > FATAL > ERROR > WARN > INFO > DEBUG  > ALL -->
  <root>
    <priority value="ALL"/>
    <level value="ALL"/>
    <appender-ref ref="rollingAppender" />
  </root>
</log4net>

2. Json操作帮助类库

 public class JsonHelper
    {
        /// <summary>
        /// 读取json文件
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public static string ReadJson(string filePath)
        {
            return File.ReadAllText(filePath);
        }

        /// <summary>
        /// 利用newtonsoft.json序列化
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="t"></param>
        /// <returns></returns>
        public static string NewtonsoftSerialiize<T>(T t)
        {
            return JsonConvert.SerializeObject(t);
        }

        /// <summary>
        ///  利用newtonsoft.json反序列化
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="content"></param>
        /// <returns></returns>
        public static T NewtonsoftDeserialize<T>(string content)
        {
            return JsonConvert.DeserializeObject <T>(content);
        }
    }

3.HTTP请求帮助类

(1)HttpRequest

 public class HttpHelper
    {
        public static string DownLoadHtmlByUrl(string url)
        {
            return DownLoadHtml(url,Encoding.UTF8);
        }


        public static string DownLoadHtml(string url, Encoding encode)
        {
            string html = string.Empty;
            try
            {
                HttpWebRequest request = HttpWebRequest.Create(url) as HttpWebRequest;//模拟请求
                request.Timeout = 30 * 1000;//设置30s超时
                request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:62.0) Gecko/20100101 Firefox/62.0";//模拟浏览器信息
                request.ContentType = "text/html; charset=utf-8";
                request.CookieContainer = new CookieContainer();
                using (HttpWebResponse response =request.GetResponse() as HttpWebResponse)//发起请求
                {
                    if(response.StatusCode!=HttpStatusCode.OK)
                    {

                    }
                    else
                    {
                        try
                        {
                            using (StreamReader read = new StreamReader(response.GetResponseStream(), encode))
                            {
                                html = read.ReadToEnd();//读取数据
                                read.Close();
                            }
                        }
                        catch (Exception ex)
                        {
                            html = null;
                            throw;
                        }
                    }
                }

            }
            catch (System.Net.WebException ex)
            {

                if (ex.Message.Equals("远程服务器返回错误: (306)。"))
                {
                   
                    html = null;
                }
            }
            catch (Exception ex)
            {
               
                html = null;
            }
            return html;
        }
    }


(2)HttpClient

        /// <summary>
        /// Get请求
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
 public class HttpClientHelper
    {
        public static string GetResponseByGet( string url)
        {
            string result = "";

            var httpclient = new HttpClient();

           
            var response = httpclient.GetAsync(url).Result;
            if (response.IsSuccessStatusCode)
            {
                Stream myResponseStream = response.Content.ReadAsStreamAsync().Result;
                StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
                result = myStreamReader.ReadToEnd();
                myStreamReader.Close();
                myResponseStream.Close();
            }

            return result;
        }
    }

        /// <summary>
        /// 模拟post表单请求
        /// </summary>
        /// <param name="url">url</param>
        /// <param name="postData">参数</param>
        /// <returns>String</returns>
        public static string HttpPost(Uri url, string postData)
        {
            string result = string.Empty;
            try
            {


                var httpCotent = new StringContent(postData);
                var httpclient = new HttpClient();
                var response = httpclient.PostAsync(url, httpCotent).Result;
                if (response.IsSuccessStatusCode)
                {
                    using (var myResponseStream = response.Content.ReadAsStreamAsync().Result)
                    {

                        using (var myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8")))
                        {
                            result = myStreamReader.ReadToEnd();
                        }
                    }

                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.ToString());
            }

            return result;
        }

4.读取程序中的appSettings.json文件

    /// <summary>
    /// 固定读取根目录下appsettings.json
    /// </summary>
    public class ConfigrationManager
    {
        //第一次使用时候初始化
        static ConfigrationManager()
        {
            var builder = new ConfigurationBuilder()
                    .SetBasePath(Directory.GetCurrentDirectory())
                    .AddJsonFile("appsettings.json");

            IConfigurationRoot configuration = builder.Build();
            // _SqlConnectionString = configuration["connectionString"];
            _SqlConnectionString = configuration.GetConnectionString("SchoolContext");
        }

        #region 数据库连接
        private static string _SqlConnectionString = null;
        public static string SqlConnectionString
        {
            get
            {
                return _SqlConnectionString;
            }
        }
        #endregion

    }
{
  "ConnectionStrings": {
    "SchoolContext": "server=localhost;userid=root;pwd=123456;port=3306;database=mytest;sslmode=none;Convert Zero Datetime=True"
  }

}

5.去重帮助类

    /// <summary>
    /// 去重帮助类
    /// </summary>
    public static class DistinctByHelper
    {

        public static IEnumerable<TSource> DistinctBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
        {
            HashSet<TKey> keys = new HashSet<TKey>();
            foreach (TSource element in source)
                if (keys.Add(keySelector(element)))
                    yield return element;
        }

    }

6.DES加密/解密帮助类

    /// <summary>
	/// DES加密/解密类。
	/// </summary>
	public class DESEncrypt
	{
		public DESEncrypt()
		{
		}





		/// <summary>
		/// 加密密码
		/// </summary>
		/// <param name="mm">原始密码</param>
		/// <returns>返回加密后的字符串</returns>
		public static string EncryptionCode(string mm)
		{
			string emm = string.Empty;
			for (int i = 0; i < mm.Length; i++)
			{
				string str = mm.Substring(mm.Length - i - 1, 1);
				string ss = string.Empty;
				byte[] asciis = Encoding.ASCII.GetBytes(str);
				for (int n = 0; n < asciis.Length; n++)
				{
					ASCIIEncoding asciiEncodeing = new ASCIIEncoding();
					byte[] byteArray = new byte[] { (byte)((int)asciis[n] - 6) };
					emm += asciiEncodeing.GetString(byteArray);
				}
			}
			return emm;
			//return mm;
		}

		/// <summary>
		/// 解密密码
		/// </summary>
		/// <param name="mm">加密后的密码</param>
		/// <returns>还原密码</returns>
		public static string DecryptCode(string mm)
		{
			string emm = string.Empty;
			for (int i = 0; i < mm.Length; i++)
			{
				string str = mm.Substring(mm.Length - i - 1, 1);
				string ss = string.Empty;
				byte[] asciis = Encoding.ASCII.GetBytes(str);
				for (int n = 0; n < asciis.Length; n++)
				{
					ASCIIEncoding asciiEncodeing = new ASCIIEncoding();
					byte[] byteArray = new byte[] { (byte)((int)asciis[n] + 6) };
					emm += asciiEncodeing.GetString(byteArray);
				}
			}
			return emm;
			//return mm;
		}

	}

7. Lambda表达式拼接扩展类

 /// <summary>
    /// Lambda表达式拼接扩展类
    /// </summary>
    public static class ExpressionHelper
    {
        /// <summary>
        /// Lambda表达式拼接
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="first"></param>
        /// <param name="second"></param>
        /// <param name="merge"></param>
        /// <returns></returns>
        public static Expression<T> Compose<T>(this Expression<T> first, Expression<T> second, Func<Expression, Expression, Expression> merge)
        {
            var map = first.Parameters.Select((f, i) => new { f, s = second.Parameters[i] }).ToDictionary(p => p.s, p => p.f);
            var secondBody = ParameterRebinder.ReplaceParameters(map, second.Body);
            return Expression.Lambda<T>(merge(first.Body, secondBody), first.Parameters);
        }
        /// <summary>
        /// and扩展
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="first"></param>
        /// <param name="second"></param>
        /// <returns></returns>

        public static Expression<Func<T1, T2, T3, T4, T5, T6, T7,T8, bool>> And<T1, T2, T3, T4, T5, T6, T7,T8>(this Expression<Func<T1, T2, T3, T4, T5, T6, T7, T8, bool>> first, Expression<Func<T1, T2, T3, T4, T5, T6, T7, T8, bool>> second)
        {
            return first.Compose(second, Expression.And);
        }

        public static Expression<Func<T1, T2, T3, T4, T5, T6, T7, T8,T9, bool>> And<T1, T2, T3, T4, T5, T6, T7, T8, T9>(this Expression<Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, bool>> first, Expression<Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, bool>> second)
        {
            return first.Compose(second, Expression.And);
        }

        public static Expression<Func<T1, T2, T3, T4, T5, T6,T7, bool>> And<T1, T2, T3, T4, T5, T6,T7>(this Expression<Func<T1, T2, T3, T4, T5, T6,T7, bool>> first, Expression<Func<T1, T2, T3, T4, T5, T6,T7, bool>> second)
        {
            return first.Compose(second, Expression.And);
        }

        public static Expression<Func<T1, T2, T3, T4, T5,T6, bool>> And<T1, T2, T3, T4, T5,T6>(this Expression<Func<T1, T2, T3, T4, T5,T6, bool>> first, Expression<Func<T1, T2, T3, T4, T5, T6, bool>> second)
        {
            return first.Compose(second, Expression.And);
        }

        public static Expression<Func<T1, T2, T3, T4,T5, bool>> And<T1, T2, T3, T4,T5>(this Expression<Func<T1, T2, T3, T4, T5, bool>> first, Expression<Func<T1, T2, T3, T4, T5, bool>> second)
        {
            return first.Compose(second, Expression.And);
        }
        public static Expression<Func<T1, T2, T3,T4, bool>> And<T1, T2, T3, T4>(this Expression<Func<T1, T2, T3, T4, bool>> first, Expression<Func<T1, T2, T3, T4, bool>> second)
        {
            return first.Compose(second, Expression.And);
        }

        public static Expression<Func<T1, T2,T3, bool>> And<T1, T2,T3>(this Expression<Func<T1, T2,T3, bool>> first, Expression<Func<T1, T2, T3, bool>> second)
        {
            return first.Compose(second, Expression.And);
        }
        public static Expression<Func<T1, T2, bool>> And<T1, T2>(this Expression<Func<T1, T2, bool>> first, Expression<Func<T1, T2, bool>> second)
        {
            return first.Compose(second, Expression.And);
        }
        public static Expression<Func<T, bool>> And<T>(this Expression<Func<T, bool>> first, Expression<Func<T, bool>> second)
        {
            return first.Compose(second, Expression.And);
        }



        /// <summary>
        /// or扩展
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="first"></param>
        /// <param name="second"></param>
        /// <returns></returns>
        public static Expression<Func<T1, T2, bool>> Or<T1, T2>(this Expression<Func<T1, T2, bool>> first, Expression<Func<T1, T2, bool>> second)
        {
            return first.Compose(second, Expression.Or);
        }
        public static Expression<Func<T, bool>> Or<T>(this Expression<Func<T, bool>> first, Expression<Func<T, bool>> second)
        {
            return first.Compose(second, Expression.Or);
        }

    }

    /// <summary>
    /// 
    /// </summary>
    public class ParameterRebinder : ExpressionVisitor
    {
        private readonly Dictionary<ParameterExpression, ParameterExpression> map;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="map"></param>
        public ParameterRebinder(Dictionary<ParameterExpression, ParameterExpression> map)
        {
            this.map = map ?? new Dictionary<ParameterExpression, ParameterExpression>();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="map"></param>
        /// <param name="exp"></param>
        /// <returns></returns>
        public static Expression ReplaceParameters(Dictionary<ParameterExpression, ParameterExpression> map, Expression exp)
        {
            return new ParameterRebinder(map).Visit(exp);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="p"></param>
        /// <returns></returns>
        protected override Expression VisitParameter(ParameterExpression p)
        {
            ParameterExpression replacement;
            if (map.TryGetValue(p, out replacement))
            {
                p = replacement;
            }
            return base.VisitParameter(p);
        }
    }

8. 去除富文本中的HTML标签

        /// <summary>
        /// 去除富文本中的HTML标签
        /// </summary>
        /// <param name="html"></param>
        /// <param name="length"></param>
        /// <returns></returns>
        public static string ReplaceHtmlTag(string html, int length = 0)
        {
            string strText = System.Text.RegularExpressions.Regex.Replace(html, "<[^>]+>", "");
            strText = System.Text.RegularExpressions.Regex.Replace(strText, "&[^;]+;", "");

            if (length > 0 && strText.Length > length)
                return strText.Substring(0, length);

            return strText;
        }

9. MD5帮助类

    /// <summary>
    /// MD5帮助类库
    /// </summary>
    public class MD5Helper
    {
        /// <summary>
        /// 16位MD5加密
        /// </summary>
        /// <param name="password"></param>
        /// <returns></returns>
        public static string MD5Encrypt16(string password)
        {
            var md5 = new MD5CryptoServiceProvider();
            string t2 = BitConverter.ToString(md5.ComputeHash(Encoding.Default.GetBytes(password)), 4, 8);
            t2 = t2.Replace("-", string.Empty);
            return t2;
        }

        /// <summary>
        /// 32位MD5加密
        /// </summary>
        /// <param name="password"></param>
        /// <returns></returns>
        public static string MD5Encrypt32(string password = "")
        {
            string pwd = string.Empty;
            try
            {
                if (!string.IsNullOrEmpty(password) && !string.IsNullOrWhiteSpace(password))
                {
                    MD5 md5 = MD5.Create(); //实例化一个md5对像
                    // 加密后是一个字节类型的数组,这里要注意编码UTF8/Unicode等的选择 
                    byte[] s = md5.ComputeHash(Encoding.UTF8.GetBytes(password));
                    // 通过使用循环,将字节类型的数组转换为字符串,此字符串是常规字符格式化所得
                    foreach (var item in s)
                    {
                        // 将得到的字符串使用十六进制类型格式。格式后的字符是小写的字母,如果使用大写(X)则格式后的字符是大写字符 
                        pwd = string.Concat(pwd, item.ToString("X2"));
                    }
                }
            }
            catch
            {
                throw new Exception($"错误的 password 字符串:【{password}】");
            }
            return pwd;
        }

        /// <summary>
        /// 64位MD5加密
        /// </summary>
        /// <param name="password"></param>
        /// <returns></returns>
        public static string MD5Encrypt64(string password)
        {
            // 实例化一个md5对像
            // 加密后是一个字节类型的数组,这里要注意编码UTF8/Unicode等的选择 
            MD5 md5 = MD5.Create();
            byte[] s = md5.ComputeHash(Encoding.UTF8.GetBytes(password));
            return Convert.ToBase64String(s);
        }

    }

10. 二维码生成帮助类

先nugut安装下:ThoughtWorks.QRCodeCore 包

/// <summary>
    /// 二维码生成帮助类
    /// </summary>
    public class QRCodeHelper
    {

       
        #region 二维码生成  
        /// <summary>  
        /// 生成二维码图片  
        /// </summary>  
        public static int Create_CodeImages(List<string> EquipAssetIDS)
        {
            try
            {

                foreach (var EquipAssetID in EquipAssetIDS)
                {
                    //生成图片  
                    Bitmap image = Create_ImgCode(EquipAssetID, 10);
                    //保存图片  
                    SaveImg(currentPath, image, EquipAssetID);
                }

                return EquipAssetIDS.Count;
            }


            catch (Exception )
            {

                return 0;
            }
        }


        //程序路径  
        readonly static string currentPath = "D:" + @"\BarCode_Images";

        /// <summary>  
        /// 保存图片  
        /// </summary>  
        /// <param name="strPath">保存路径</param>  
        /// <param name="img">图片</param>  
        public static void SaveImg(string strPath, Bitmap img, string SBBH)
        {
            //保存图片到目录  
            if (Directory.Exists(strPath))
            {
                //文件名称  
                string guid = SBBH.ToString().Replace("-", "") + ".png";
                img.Save(strPath + "/" + guid, System.Drawing.Imaging.ImageFormat.Png);
            }
            else
            {
                //当前目录不存在,则创建  
                Directory.CreateDirectory(strPath);
            }
        }
        /// <summary>  
        /// 生成二维码图片  
        /// </summary>  
        /// <param name="codeNumber">要生成二维码的字符串</param>       
        /// <param name="size">大小尺寸</param>  
        /// <returns>二维码图片</returns>  
        public static Bitmap Create_ImgCode(string codeNumber, int size)
        {
            //创建二维码生成类  
            QRCodeEncoder qrCodeEncoder = new QRCodeEncoder();
            //设置编码模式  
            qrCodeEncoder.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.BYTE;
            //设置编码测量度  
            qrCodeEncoder.QRCodeScale = size;
            //设置编码版本  
            qrCodeEncoder.QRCodeVersion = 0;
            //设置编码错误纠正  
            qrCodeEncoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.M;

            //设置二维码前景色
            qrCodeEncoder.QRCodeForegroundColor = System.Drawing.ColorTranslator.FromHtml("#0167AF");

            //生成二维码图片  
            System.Drawing.Bitmap image = qrCodeEncoder.Encode(codeNumber, Encoding.UTF8);
            return image;
        }
  
        /// <summary>  
        /// 删除目录下所有文件  
        /// </summary>  
        /// <param name="aimPath">路径</param>  
        public static void DeleteDir(string aimPath)
        {
            try
            {
                //目录是否存在  
                if (Directory.Exists(aimPath))
                {
                    // 检查目标目录是否以目录分割字符结束如果不是则添加之  
                    if (aimPath[aimPath.Length - 1] != Path.DirectorySeparatorChar)
                        aimPath += Path.DirectorySeparatorChar;
                    // 得到源目录的文件列表,该里面是包含文件以及目录路径的一个数组  
                    // 如果你指向Delete目标文件下面的文件而不包含目录请使用下面的方法  
                    string[] fileList = Directory.GetFiles(aimPath);
                    //string[] fileList = Directory.GetFileSystemEntries(aimPath);  
                    // 遍历所有的文件和目录  
                    foreach (string file in fileList)
                    {
                        // 先当作目录处理如果存在这个目录就递归Delete该目录下面的文件  
                        if (Directory.Exists(file))
                        {
                            DeleteDir(aimPath + Path.GetFileName(file));
                        }
                        // 否则直接Delete文件  
                        else
                        {
                            File.Delete(aimPath + Path.GetFileName(file));
                        }
                    }
                }
            }
            catch (Exception e)
            {
                throw e;
            }
        }
        #endregion



    }

11. 序列化反序列化帮助类

    /// <summary>
    /// 序列化反序列化帮助类
    /// </summary>
    public class SerializeHelper
    {
        /// <summary>
        /// 序列化
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        public static byte[] Serialize(object item)
        {
            var jsonString = JsonConvert.SerializeObject(item);

            return Encoding.UTF8.GetBytes(jsonString);
        }
        /// <summary>
        /// 反序列化
        /// </summary>
        /// <typeparam name="TEntity"></typeparam>
        /// <param name="value"></param>
        /// <returns></returns>
        public static TEntity Deserialize<TEntity>(byte[] value)
        {
            if (value == null)
            {
                return default(TEntity);
            }
            var jsonString = Encoding.UTF8.GetString(value);
            return JsonConvert.DeserializeObject<TEntity>(jsonString);
        }
    }

12. redis帮助类

 /// <summary>
    /// Redis缓存接口
    /// </summary>
    public interface IRedisCacheManager
    {

        //获取 Reids 缓存值
        string GetValue(string key);

        //获取值,并序列化
        TEntity Get<TEntity>(string key);

        //保存
        void Set(string key, object value, TimeSpan cacheTime);

        //判断是否存在
        bool Get(string key);

        //移除某一个缓存值
        void Remove(string key);

        //全部清除
        void Clear();
    }

 /// <summary>
    /// redis帮助类
    /// </summary>
    public class RedisCacheManager : IRedisCacheManager
    {

        private readonly string redisConnenctionString;

        public volatile ConnectionMultiplexer redisConnection;

        private readonly object redisConnectionLock = new object();

        public RedisCacheManager()
        {
            string redisConfiguration = Appsettings.App(new string[] { "ConnectionStrings", "RedisConnectionString" });//获取连接字符串

            if (string.IsNullOrWhiteSpace(redisConfiguration))
            {
                throw new ArgumentException("redis config is empty", nameof(redisConfiguration));
            }
            this.redisConnenctionString = redisConfiguration;
            this.redisConnection = GetRedisConnection();
        }

        /// <summary>
        /// 核心代码,获取连接实例
        /// 通过双if 夹lock的方式,实现单例模式
        /// </summary>
        /// <returns></returns>
        private ConnectionMultiplexer GetRedisConnection()
        {
            //如果已经连接实例,直接返回
            if (this.redisConnection != null && this.redisConnection.IsConnected)
            {
                return this.redisConnection;
            }
            //加锁,防止异步编程中,出现单例无效的问题
            lock (redisConnectionLock)
            {
                if (this.redisConnection != null)
                {
                    //释放redis连接
                    this.redisConnection.Dispose();
                }
                try
                {
                    var config = new ConfigurationOptions
                    {
                        AbortOnConnectFail = false,
                        AllowAdmin = true,
                        ConnectTimeout = 15000,//改成15s
                        SyncTimeout = 5000,
                        //Password = "Pwd",//Redis数据库密码
                        EndPoints = { redisConnenctionString }// connectionString 为IP:Port 如”192.168.2.110:6379”
                    };
                    this.redisConnection = ConnectionMultiplexer.Connect(config);
                }
                catch (Exception)
                {
                    //throw new Exception("Redis服务未启用,请开启该服务,并且请注意端口号,本项目使用的的6319,而且我的是没有设置密码。");
                }
            }
            return this.redisConnection;
        }
        /// <summary>
        /// 清除
        /// </summary>
        public void Clear()
        {
            foreach (var endPoint in this.GetRedisConnection().GetEndPoints())
            {
                var server = this.GetRedisConnection().GetServer(endPoint);
                foreach (var key in server.Keys())
                {
                    redisConnection.GetDatabase().KeyDelete(key);
                }
            }
        }
        /// <summary>
        /// 判断是否存在
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public bool Get(string key)
        {
            return redisConnection.GetDatabase().KeyExists(key);
        }

        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public string GetValue(string key)
        {
            return redisConnection.GetDatabase().StringGet(key);
        }

        /// <summary>
        /// 获取
        /// </summary>
        /// <typeparam name="TEntity"></typeparam>
        /// <param name="key"></param>
        /// <returns></returns>
        public TEntity Get<TEntity>(string key)
        {
            var value = redisConnection.GetDatabase().StringGet(key);
            if (value.HasValue)
            {
                //需要用的反序列化,将Redis存储的Byte[],进行反序列化
                return SerializeHelper.Deserialize<TEntity>(value);
            }
            else
            {
                return default(TEntity);
            }
        }

        /// <summary>
        /// 移除
        /// </summary>
        /// <param name="key"></param>
        public void Remove(string key)
        {
            redisConnection.GetDatabase().KeyDelete(key);
        }
        /// <summary>
        /// 设置
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        /// <param name="cacheTime"></param>
        public void Set(string key, object value, TimeSpan cacheTime)
        {
            if (value != null)
            {
                //序列化,将object值生成RedisValue
                redisConnection.GetDatabase().StringSet(key, SerializeHelper.Serialize(value), cacheTime);
            }
        }

        /// <summary>
        /// 增加/修改
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public bool SetValue(string key, byte[] value)
        {
            return redisConnection.GetDatabase().StringSet(key, value, TimeSpan.FromSeconds(120));
        }

    }

13. HttpRequestExtension

    public class DynamicQueryParams
    {
        public string QueryKeys { get; set; }

        public ICollection<object> QueryValues { get; set; }
    }

    public static class HttpRequestExtensions
    {
        public static DynamicQueryParams GetDynamicParams([NotNull] this IQueryCollection query)
        {
            var keyAry = new List<string>();
            var valAry = new List<object>();
            GetKeyVals(query, keyAry, valAry);

            if (!valAry.Any())
            {
                keyAry.Add($"1=@0");
                valAry.Add(1);
            }

            return new DynamicQueryParams { QueryKeys = string.Join(" and ", keyAry), QueryValues = valAry };
        }

        private static void GetKeyVals(IQueryCollection items, List<string> keyAry, List<object> valAry)
        {
            var ignoreFields = new List<string> { "pageindex", "pagesize" };
            var index = 0;
            foreach (var item in items)
            {
                if (ignoreFields.Any(f => item.Key.Equals(f, StringComparison.CurrentCultureIgnoreCase)))
                {
                    continue;
                }

                if (StringValues.IsNullOrEmpty(item.Value))
                {
                    continue;
                }

                var curVal = item.Value.ToString();
                if (string.IsNullOrWhiteSpace(curVal))
                {
                    continue;
                }

                string queryVal = curVal;
                var queryStatement = GetStatement(item.Key, curVal, index, ref queryVal);
                keyAry.Add(queryStatement);
                valAry.Add(queryVal);
                index++;
            }
        }

        private static string GetStatement(string key, string val, int index, ref string queryVal)
        {
            string result = $"{key}=@{index}";

            queryVal = val;
            var regex = new System.Text.RegularExpressions.Regex("(^-[0-9]{2}-)");
            if (!regex.IsMatch(val))
            {
                return result;
            }

            var queryOperator = regex.Match(val).Value.Trim();
            if (string.IsNullOrEmpty(queryOperator))
            {
                return result;
            }

            switch (queryOperator)
            {
                case "-01-":
                    result = $"{key}=@{index}";  //等于
                    break;

                case "-02-":
                    result = $"{key}.Contains(@{index})";  //包含
                    break;

                case "-03-":
                    result = $"{key}>@{index}";  //大于
                    break;

                case "-04-":
                    result = $"{key}>=@{index}";  //大于等于
                    break;

                case "-05-":
                    result = $"{key}<@{index}";  //小于
                    break;

                case "-06-":
                    result = $"{key}<=@{index}";  //小于等于
                    break;

                default:
                    result = $"{key}=@{index}";
                    break;
            }

            regex = new System.Text.RegularExpressions.Regex("(?<=^-[0-9]{2}-).*");
            if (regex.IsMatch(val))
            {
                var tmp = regex.Match(val).Value.Trim();
                if (!string.IsNullOrEmpty(tmp))
                {
                    queryVal = tmp;
                }
            }

            return result;
        }
    }

14. 检查集合是否为空

public static class IEnumerableExtension
{       
    public static IEnumerable<T> Safe<T>(this IEnumerable<T> source)
    {
        if (source == null)
        {
            yield break;
        }

        foreach (var item in source)
        {
            yield return item;
        }
    }
}

if (myList.Safe().Any())
 {
      //执行逻辑
 }

15. FTP帮助类库

 public class FTPHelper
    {
        /// <summary>
        /// FTP文件上传
        /// </summary>
        /// <param name="buffer"></param>
        /// <param name="RemoteFileName"></param>
        /// <param name="Host"></param>
        /// <param name="UserName"></param>
        /// <param name="Userpwd"></param>
        /// <exception cref="Exception"></exception>
        public void FTPUploadFile(byte[] buffer, string RemoteFileName, string Host, string UserName, string Userpwd)
        {
            try
            {
                string serverPath = "ftp://" + Host;
                if (!serverPath.EndsWith("/"))
                    serverPath += "/";
                serverPath += RemoteFileName;
                FtpWebRequest req = (FtpWebRequest)WebRequest.Create(new Uri(serverPath));
                req.Method = WebRequestMethods.Ftp.UploadFile;
                req.UseBinary = true;
                req.Credentials = new NetworkCredential(UserName, Userpwd);// 登录凭证   
                req.ContentLength = buffer.Length;
                int bufferSize = buffer.Length;
                int length;
                int seek = 0;
                // 将文件流存在FileStream中   
                using (MemoryStream fs = new MemoryStream(buffer))
                {
                    // 上传流指向Stream   
                    using (Stream stream = req.GetRequestStream())
                    {
                        // 读取文件流中最大长度为bufferSize字节内容至buffer,读取长度返回至length   
                        length = fs.Read(buffer, 0, bufferSize);
                        // 如果读取到了内容   
                        while (length != 0)
                        {
                            //buffer写入上传流   
                            stream.Write(buffer, 0, length);
                            seek += length;
                            //继续读取   
                            length = fs.Read(buffer, 0, bufferSize);
                        }
                    }
                }
                FtpWebResponse response = req.GetResponse() as FtpWebResponse;
                response.Close();
            }
            catch (Exception ex)
            {
                throw new Exception(string.Format("FTPUploadFile错误,原因:{0}", ex.Message));
            }
        }

        public void FTPNoUserNamePwdUploadFile(byte[] buffer, string RemoteFileName, string Host, string UserName, string Userpwd)
        {
            try
            {
                string serverPath = "ftp://" + Host;
                if (!serverPath.EndsWith("/"))
                    serverPath += "/";
                serverPath += RemoteFileName;
                FtpWebRequest req = (FtpWebRequest)WebRequest.Create(new Uri(serverPath));
                req.Method = WebRequestMethods.Ftp.UploadFile;
                req.UseBinary = true;
                //req.Credentials = new NetworkCredential(UserName, Userpwd);// 登录凭证   
                req.ContentLength = buffer.Length;
                int bufferSize = buffer.Length;
                int length;
                int seek = 0;
                // 将文件流存在FileStream中   
                using (MemoryStream fs = new MemoryStream(buffer))
                {
                    // 上传流指向Stream   
                    using (Stream stream = req.GetRequestStream())
                    {
                        // 读取文件流中最大长度为bufferSize字节内容至buffer,读取长度返回至length   
                        length = fs.Read(buffer, 0, bufferSize);
                        // 如果读取到了内容   
                        while (length != 0)
                        {
                            //buffer写入上传流   
                            stream.Write(buffer, 0, length);
                            seek += length;
                            //继续读取   
                            length = fs.Read(buffer, 0, bufferSize);
                        }
                    }
                }
                FtpWebResponse response = req.GetResponse() as FtpWebResponse;
                response.Close();
            }
            catch (Exception ex)
            {
                throw new Exception(string.Format("FTPNoUserNamePwdUploadFile错误,原因:{0}", ex.Message));
            }
        }

        /// <summary>
        /// 下载
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="fileName"></param>
        public Stream ReadFtpFile(string PdfName, string UserName, string Userpwd)
        {
            var uri = new Uri(PdfName);

            var request = WebRequest.Create(uri);
            //设置请求的方法是FTP文件下载
            request.Method = WebRequestMethods.Ftp.DownloadFile;

            //连接登录FTP服务器
            request.Credentials = new NetworkCredential(UserName, Userpwd);

            //获取一个请求响应对象
            var response = request.GetResponse();
            //获取请求的响应流
            var responseStream = response.GetResponseStream();
            return responseStream;

        }
        public byte[] StreamToBytes(string PdfName)
        {
            try
            {
                var uri = new Uri(PdfName);
                var request = (HttpWebRequest)WebRequest.Create(uri);
                request.Timeout = 10000;
                WebResponse response = request.GetResponse();
                Stream stream = response.GetResponseStream();

                var memoryStream = new MemoryStream();
                //将基础流写入内存流
                const int bufferLength = 1024;
                byte[] buffer = new byte[bufferLength];
                int actual = stream.Read(buffer, 0, bufferLength);
                if (actual > 0)
                {
                    memoryStream.Write(buffer, 0, actual);
                }
                memoryStream.Position = 0;
                byte[] bytes = new byte[stream.Length];
                try
                {
                    stream.Read(bytes, 0, bytes.Length);
                    // 设置当前流的位置为流的开始
                    stream.Seek(0, SeekOrigin.Begin);
                    return bytes;
                }
                catch
                {
                }
                return bytes;
            }
            catch
            {
                return null;
            }
        }

        public byte[] FileDownload(string ftpFileName)
        {
            FtpWebRequest ftpWebRequest = null;
            FtpWebResponse ftpWebResponse = null;
            Stream ftpResponseStream = null;
            FileStream outputStream = null;
            byte[] byteResult = null;
            try
            {
                string uri = ftpFileName;
                ftpWebRequest = (FtpWebRequest)WebRequest.Create(new Uri(uri));
                ftpWebRequest.UseBinary = true;
                ftpWebRequest.Method = WebRequestMethods.Ftp.DownloadFile;
                ftpWebResponse = (FtpWebResponse)ftpWebRequest.GetResponse();
                ftpResponseStream = ftpWebResponse.GetResponseStream();
                List<byte> byteList = new List<byte>();
                int i = 0;
                while ((i = ftpResponseStream.ReadByte()) != -1)
                {
                    byteList.Add((byte)i);
                }
                byteResult = byteList.ToArray();
            }
            catch (Exception ex)
            {
                throw new Exception(string.Format("FileDownload错误,原因:{0}", ex.Message));
            }
            finally
            {
                outputStream.Close();
                ftpResponseStream.Close();
                ftpWebResponse.Close();
            }
            return byteResult;
        }

        public static byte[] FileDownloadByUserPwd(string ftpFileName, string ftpUser, string ftpPwd)
        {
            FtpWebRequest ftpWebRequest = null;
            FtpWebResponse ftpWebResponse = null;
            Stream ftpResponseStream = null;
            FileStream outputStream = null;
            byte[] byteResult = null;
            try
            {
                string uri = ftpFileName;
                ftpWebRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
                ftpWebRequest.Credentials = new NetworkCredential(ftpUser, ftpPwd);
                ftpWebRequest.UseBinary = true;
                ftpWebRequest.Method = WebRequestMethods.Ftp.DownloadFile;
                ftpWebResponse = (FtpWebResponse)ftpWebRequest.GetResponse();
                ftpResponseStream = ftpWebResponse.GetResponseStream();
                List<byte> byteList = new List<byte>();
                int i = 0;
                while ((i = ftpResponseStream.ReadByte()) != -1)
                {
                    byteList.Add((byte)i);
                }
                byteResult = byteList.ToArray();
            }
            catch (Exception ex)
            {
                throw new Exception(string.Format("FileDownloadByUserPwd错误,原因:{0}", ex.Message));
            }
            finally
            {
                outputStream.Close();
                ftpResponseStream.Close();
                ftpWebResponse.Close();
            }
            return byteResult;
        }
    }
## 比较全面的c#帮助 日常工作总结,加上网上收集,各式各样的几乎都能找到,所有功能性代码都是独立的之间没有联系,可以单独引用至项目,分享出来,方便大家,几乎都有注释,喜欢的请点赞,不断完善收集中... ## 样板图片操作 ![WEFE@M%}SN4_K$6H0D{6IYJ.png](http://upload-images.jianshu.io/upload_images/6855212-34f0ee0339e3cb49.png?imageMogr2/auto-orient/strip|imageView2/2/w/1240) ## 操作文档 里面包含一下操作文档,这个是用Sandcastle工具生成的。方法:四种Sandcastle方法生成c#.net帮助帮助文档,地址:http://www.cnblogs.com/anyushengcms/p/7682501.html ![H819EQUYFVA~WXK6YAQ1%6Q.png](http://upload-images.jianshu.io/upload_images/6855212-6cf5a7a2a4a75c89.png?imageMogr2/auto-orient/strip|imageView2/2/w/1240) ## 附上一些常见的帮助栏目 1. cookie操作 --------- CookieHelper.cs 2. session操作 ------- SessionHelper.cs 3. cache操作 4. ftp操作 5. http操作 ------------ HttpHelper.cs 6. json操作 ------------ JsonHelper.cs 7. xml操作 ------------- XmlHelper.cs 8. Excel操作 9. Sql操作 ------------- SqlHelper.cs 10. 型转换 ------------ Converter.cs 11. 加密解密 ------------ EncryptHelper.cs 12. 邮件发送 ------------ MailHelper.cs 13. 二维码 14. 汉字转拼音 15. 计划任务 ------------ IntervalTask.cs 16. 信息配置 ------------ Setting.cs 17. 上传下载配置文件操作 18. 视频转换 19. 图片操作 20. 验证码生成 21. String拓展 ---------- StringExtension.cs 22. 正则表达式 --------- RegexHelper.cs 23. 分页操作 24. UBB编码 25. Url重写 26. Object拓展 --------- ObjectExtension.cs 27. Stream的拓展 ------ StreamExtension.cs 28. CSV文件转换 29. Chart图形 30. H5-微信 31. PDF 32. 分词辅助 33. 序列化 34. 异步线程 35. 弹出消息 36. 文件操作 37. 日历 38. 日志 39. 时间操作 40. 时间戳 41. 条形码 42. 正则表达式 43. 汉字转拼音 44. 网站安全 45. 网络 46. 视频转换 47. 计划任务 48. 配置文件操作 49. 阿里云 50. 随机数 51. 页面辅助 52. 验证码 53. Mime 54. Net 55. NPOI 56. obj 57. Path 58. Properties 59. ResourceManager 60. URL的操作 61. VerifyCode 62. 处理多媒体的公共 63. 各种验证帮助 64. 分页 65. 计划任务 66. 配置文件操作 67. 分词辅助 68. IP辅助 69. Html操作
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值