• c#一些常用的方法集合


    是从一个asp.net mvc的项目里看到的。挺实用的。


    通过身份证号码获取出生日期和性别




    通过身份证号码获取出生日期和性别

     #region 由身份证获得出生日期
        public static string CardBrith(string CardNo)
        {
            return CardNo.Substring(6, 4) + "-" + CardNo.Substring(10, 2) + "-" + CardNo.Substring(12, 2);
        }
        #endregion
    
        #region 由身份证获得性别
        public static string CardSex(string CardNo)
        {
            string sSex = "";
            int sex = Convert.ToInt16(CardNo.Substring(16, 1));
            if (sex % 2 == 0)//性别代码为偶数是女性奇数为男性
            {
                sSex = "";
            }
            else
            {
                sSex = "";
            }
            return sSex;
        }
        #endregion






    验证身份证号码:

     #region 验证身份证号码
        /// <summary>
        /// 验证身份证号码,正确返回true
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public static bool CardNO(string Id)
        {
    
            long n = 0;
    
            if (long.TryParse(Id.Remove(17), out n) == false || n < Math.Pow(10, 16) || long.TryParse(Id.Replace('x', '0').Replace('X', '0'), out n) == false)
            {
    
                return false;//数字验证
    
            }
    
            string address = "11x22x35x44x53x12x23x36x45x54x13x31x37x46x61x14x32x41x50x62x15x33x42x51x63x21x34x43x52x64x65x71x81x82x91";
    
            if (address.IndexOf(Id.Remove(2)) == -1)
            {
    
                return false;//省份验证
    
            }
    
            string birth = Id.Substring(6, 8).Insert(6, "-").Insert(4, "-");
    
            DateTime time = new DateTime();
    
            if (DateTime.TryParse(birth, out time) == false)
            {
    
                return false;//生日验证
    
            }
    
            string[] arrVarifyCode = ("1,0,x,9,8,7,6,5,4,3,2").Split(',');
    
            string[] Wi = ("7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2").Split(',');
    
            char[] Ai = Id.Remove(17).ToCharArray();
    
            int sum = 0;
    
            for (int i = 0; i < 17; i++)
            {
    
                sum += int.Parse(Wi[i]) * int.Parse(Ai[i].ToString());
    
            }
    
            int y = -1;
    
            Math.DivRem(sum, 11, out y);
    
            if (arrVarifyCode[y] != Id.Substring(17, 1).ToLower())
            {
    
                return false;//校验码验证
    
            }
    
            return true;//符合GB11643-1999标准
    
        }
        #endregion






    字符串解码

     1 #region 字符串解码
     2     /// <summary>
     3     /// 字符串解码
     4     /// </summary>
     5     /// <param name="str">原字符</param>
     6     /// <returns>解码后的字符</returns>
     7     public static string StrDecode(string str)
     8     {
     9         if (string.IsNullOrEmpty(str)) { return str; }
    10         return System.Web.HttpUtility.HtmlDecode(str); ;
    11     }
    12     #endregion







    字符串编码

     1 #region 字符串编码
     2     /// <summary>
     3     /// 目前只做字符串编码
     4     /// </summary>
     5     /// <param name="str">原字符</param>
     6     /// <returns>编码后的字符</returns>
     7     public static string StrEncode(string str)
     8     {
     9         if (string.IsNullOrEmpty(str)) { return str; }
    10         return System.Web.HttpUtility.HtmlEncode(str);
    11     }
    12     #endregion






    获得分页记录

     1     #region 获得分页记录
     2     /// <summary>
     3     /// 获得分页记录,返回DataTable类型
     4     /// </summary>
     5     /// <param name="tblName">表名</param>
     6     /// <param name="strGetFields">需返回的字段</param>
     7     /// <param name="strWhere">条件</param>
     8     /// <param name="OrderType">排序字段</param>
     9     /// <param name="PageIndex">当前页面</param>
    10     /// <param name="PageSize">页尺寸</param>
    11     /// <returns>返回DataTable类型</returns>
    12     public static DataTable GetPageData(string tblName, string strGetFields, string strWhere, string OrderType, int PageIndex, int PageSize)
    13     {
    14         SqlParameter[] para = {
    15                     new SqlParameter("@Table", SqlDbType.VarChar, 1000){Value=tblName},//表名   
    16                     new SqlParameter("@Fields", SqlDbType.VarChar, 5000){Value=strGetFields},//返回的列 
    17                     new SqlParameter("@Where", SqlDbType.VarChar, 1000){Value=strWhere},//where条件  
    18                     new SqlParameter("@OrderBy",SqlDbType.VarChar, 500){Value=OrderType},//排序 
    19                     new SqlParameter("@CurrentPage",SqlDbType.Int,4){Value=PageIndex},//页码   
    20                     new SqlParameter("@PageSize", SqlDbType.Int,4){Value=PageSize}//页尺寸
    21                               };
    22         DataTable dt = new DataTable();
    23         XBSQL.RunProc("Pages", out dt, para);
    24         return dt;
    25     }
    26     #endregion






    获得符合条件指定列的和

     1     #region 获得符合条件指定列的和
     2     /// <summary>
     3     /// 返回符合条件指定列的和
     4     /// </summary>
     5     /// <param name="Field"></param>
     6     /// <param name="TableName">表名</param>
     7     /// <param name="WhereSql">条件</param>
     8     /// <returns></returns>
     9     public static double RsSum(string Field, string TableName, string WhereSql)
    10     {
    11         string Num = XBSQL.EScalar("select sum(" + Field + ") from " + TableName + " where " + WhereSql + "").ToString();
    12         Num = (string.IsNullOrEmpty(Num)) ? "0" : Num;
    13         return Convert.ToDouble(Num);
    14     }
    15 
    16     #endregion






    获取记录总和

     1     #region 获得记录总数
     2     /// <summary>
     3     /// 获得满足条件的记录总数
     4     /// </summary>
     5     /// <param name="TableName">表名</param>
     6     /// <param name="WhereSql">条件</param>
     7     /// <returns></returns>
     8     public static int RsCount(string TableName, string WhereSql)
     9     {
    10         int i = 0;
    11         int.TryParse(XBSQL.EScalar("select Count(*) from " + TableName + " where " + WhereSql + "").ToString(), out i);
    12         return i;
    13         //return Convert.ToInt32(XBSQL.EScalar("select Count(*) from " + TableName + " where " + WhereSql + ""));
    14     }
    15     #endregion
    
    
    
    
    
    
    
    
    
    
    
    



    根据参数读取数据库,获取多条记录单个字段
     1  #region 根据参数读取数据库,获取多条记录单个字段
     2     /// <summary>
     3     /// 获取多条记录单个字段
     4     /// </summary>
     5     /// <param name="field"></param>
     6     /// <param name="table"></param>
     7     /// <param name="where"></param>
     8     /// <returns></returns>
     9     public static string RDSQL(string field, string table, string where)
    10     {
    11         StringBuilder Str = new StringBuilder();
    12         try
    13         {
    14             string sql = "select " + field + " from " + table + " where " + where + "";
    15             SqlDataReader dr = XBSQL.EReader(sql);
    16             while (dr.Read())
    17             {
    18                 Str.Append("," + dr[0].ToString().Trim());
    19             }
    20             dr.Close();
    21             if (Str.Length > 0)
    22             {
    23                 Str.Remove(0, 1);
    24                 return Str.ToString();
    25             }
    26             else
    27             {
    28                 return "";
    29             }
    30         }
    31         catch (Exception Error)
    32         {
    33 
    34         }
    35         finally
    36         {
    37             Str.Length = 0;
    38         }
    39         return "";
    40     }
    41     #endregion








    字符串截取

        #region 字符串截取
        /// <summary>
        /// str为要进行截取的字符串,start是第一个关键字(字符串),last是第二个关键字(字符串),n截取字符串方式   
        /// </summary>
        /// <param name="str"></param>
        /// <param name="start"></param>
        /// <param name="last"></param>
        /// <param name="n"></param>
        /// <returns></returns>
        public static string GetContent(string str, string start, string last, int n)
        {
            string ResStr = "";
            if (str.ToLower().IndexOf(start.ToLower()) >= 0)
            {
                if (str.ToLower().IndexOf(last.ToLower()) >= 0)
                {
                    switch (n)
                    {
                        //左右都截取(都取前面)(包含关键字)        
                        case 1: ResStr = str.Substring(str.ToLower().IndexOf(start.ToLower()), str.Length - str.ToLower().IndexOf(start.ToLower()));
                            ResStr = ResStr.Substring(0, ResStr.ToLower().IndexOf(last.ToLower()) + last.Length); break;
                        //左右都截取(都取前面)(去除关键字)                     
                        case 2: ResStr = str.Substring(str.ToLower().IndexOf(start.ToLower()) + start.Length, str.Length - str.ToLower().IndexOf(start.ToLower()) - start.Length);
                            ResStr = ResStr.Substring(0, ResStr.ToLower().IndexOf(last.ToLower())); break;
                        default: ResStr = ""; break;
                    }
                }
            }
            return ResStr;
        }
        public static string GetContent(string str, string start, int n)
        {
            string ResStr = "";
            switch (n)
            {
                //只往左截取(取前面的)(包含关键字)            
                case 1: ResStr = str.Substring(0, str.ToLower().IndexOf(start.ToLower()) + start.Length); break;
                //只往左截取(取前面的)(去除关键字)                     
                case 2:
                    int StrIndex = str.ToLower().IndexOf(start.ToLower());
                    if (StrIndex > 0)
                    {
                        ResStr = str.Substring(0, StrIndex);
                    }
                    break;
                //只往右截取(取前面的)(包含关键字)
                case 3: ResStr = str.Substring(str.ToLower().IndexOf(start.ToLower()), str.Length - str.ToLower().IndexOf(start.ToLower())); break;
                //只往右截取(取前面的)(去除关键字)
                case 4: ResStr = str.Substring(str.ToLower().IndexOf(start.ToLower()) + start.Length, str.Length - str.ToLower().IndexOf(start.ToLower()) - start.Length); break;
                default: ResStr = ""; break;
            }
            return ResStr;
        }
        #endregion






     判断ip格式

     1  #region 判断是否是IP格式
     2     /// <summary>  
     3     /// 判断是否是IP地址格式 0.0.0.0  
     4     /// </summary>  
     5     /// <param name="str1">待判断的IP地址</param>  
     6     /// <returns>true or false</returns>  
     7     public static bool IsIPAddress(string str1)
     8     {
     9         if (str1 == null || str1 == string.Empty || str1.Length < 7 || str1.Length > 15) return false;
    10         string regformat = @"^d{1,3}[.]d{1,3}[.]d{1,3}[.]d{1,3}$";
    11         Regex regex = new Regex(regformat, RegexOptions.IgnoreCase);
    12         return regex.IsMatch(str1);
    13     }
    14     #endregion






    获取ip

     #region 获得IP
        /// <summary>   
        /// 取得客户端真实IP。如果有代理则取第一个非内网地址   
        /// </summary>   
        public static string IPAddress
        {
            get
            {
                string result = String.Empty;
                result = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
                if (result != null && result != String.Empty)
                {
                    //可能有代理   
                    if (result.IndexOf(".") == -1)    //没有"."肯定是非IPv4格式   
                        result = null;
                    else
                    {
                        if (result.IndexOf(",") != -1)
                        {
                            //有",",估计多个代理。取第一个不是内网的IP。
                            result = result.Replace(" ", "").Replace(""", "");
                            string[] temparyip = result.Split(",;".ToCharArray());
                            for (int i = 0; i < temparyip.Length; i++)
                            {
                                if (IsIPAddress(temparyip[i])
                                    && temparyip[i].Substring(0, 3) != "10."
                                    && temparyip[i].Substring(0, 7) != "192.168"
                                    && temparyip[i].Substring(0, 7) != "172.16.")
                                {
                                    return temparyip[i];    //找到不是内网的地址   
                                }
                            }
                        }
                        else if (IsIPAddress(result)) //代理即是IP格式   
                            return result;
                        else
                            result = null;    //代理中的内容 非IP,取IP   
                    }
                }
                string IpAddress = (HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null && HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != String.Empty) ? HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] : HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
                if (null == result || result == String.Empty)
                    result = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
                if (result == null || result == String.Empty)
                    result = HttpContext.Current.Request.UserHostAddress;
                return result;
            }
        }
        #endregion







    转换成日期格式

     1 #region 转换成日期格式
     2     /// <summary>
     3     /// 转换成日期格式,非日期返回空值
     4     /// </summary>
     5     /// <param name="Str"></param>
     6     /// <returns></returns>
     7     public static string ToDate(string Str, string Format)
     8     {
     9         DateTime LDate;
    10         DateTime dt1 = DateTime.Parse("1900-01-01");
    11         DateTime dt2 = DateTime.Parse("9999-12-31");
    12         if (DateTime.TryParse(Str, out LDate) && DateTime.Compare(LDate, dt1) > 0 && DateTime.Compare(LDate, dt2) < 0)
    13         {
    14             Str = LDate.ToString("" + Format + "");
    15         }
    16         else
    17         {
    18             Str = "";
    19         }
    20         return Str.Trim();
    21     }
    22     #endregion
  • 相关阅读:
    更换pip源到国内镜像
    概率图模型学习笔记:HMM、MEMM、CRF
    xgboost入门与实战
    XGBoost浅入浅出
    使用word2vec训练中文词向量
    我为何放弃Gulp与Grunt,转投npm scripts(上)
    POJ 1265:Area
    Android网络缓存的实现思路
    设计模式:单例模式的写法(基础写法和线程安全写法)
    DFA 算法实现关键词匹配
  • 原文地址:https://www.cnblogs.com/ashidamana/p/5092061.html
Copyright © 2020-2023  润新知