C#常用函数

来源:互联网 发布:网络收纳管理咨询机构 编辑:程序博客网 时间:2024/06/01 18:55

/// <summary>
/// 获取字符串或汉字的长度
/// </summary>
/// <param name="str">字符串或汉字</param>
/// <returns>长度</returns>
public static int GetStrLength(string str)
{
   if(str==null||str==string.Empty)
   {
    return 0;
   }
   else
   {
    return System.Text.Encoding.Default.GetByteCount(str);
   }
}

/// <summary>
/// 获取随即数
/// </summary>
/// <returns></returns>
public static string GetCode()
{
   string checkCode = string.Empty;
   Random ro=new Random(System.Guid.NewGuid().GetHashCode());
   checkCode = DateTime.Now.ToString("yyyyMMddHHmmss") + ro.Next(99999);
  
   return checkCode;
}

/// <summary>
/// 判断时候是数字组合
/// </summary>
/// <param name="strDate"></param>
/// <returns></returns>
public static bool IsNumber(string strDate)
{
   if (strDate == null)
   {
    return false;
   }
   if (strDate.Equals(string.Empty))
   {
    return false;
   }

   Regex numRegex = new Regex(@"0*[0-9][0-9]*$");
   return numRegex.IsMatch(strDate);
}

/// <summary>
/// 判断是不是合法的email
/// </summary>
/// <param name="strDate"></param>
/// <returns></returns>
public static bool IsEmail(string strDate)
{
   Regex mailRegex = new Regex(@"/w+([-+.]/w+)*@/w+([-.]/w+)*/./w+([-.]/w+)*$");
   return mailRegex.IsMatch(strDate);
}

/// <summary>
/// 判断是不是合法的日期
/// </summary>
/// <param name="strDate"></param>
/// <returns></returns>
public static bool IsDate(string strDate)
{
   if (strDate == null)
   {
    return false;
   }
   Regex dateRegex = new Regex(@"^((/d{2}(([02468][048])|([13579][26]))[/-///s]?((((0?[13578])|(1[02]))[/-///s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[/-///s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[/-///s]?((0?[1-9])|([1-2][0-9])))))|(/d{2}(([02468][1235679])|([13579][01345789]))[/-///s]?((((0?[13578])|(1[02]))[/-///s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[/-///s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[/-///s]?((0?[1-9])|(1[0-9])|(2[0-8]))))))(/s(((0?[0-9])|([1-2][0-3]))/:([0-5]?[0-9])((/s)|(/:([0-5]?[0-9])))))?$");
   return dateRegex.IsMatch(strDate);
}

/// <summary>
/// 昵称规则
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static bool IsNickName(string str)
{
   Regex oReg = new Regex(@"^([/u4e00-/u9fa5]+|[a-zA-Z0-9]+)$");
   if(oReg.IsMatch(str))
   {
    return true;
   }
   return false;
}

/// <summary>
      /// 常用过滤字符
      ///防止注入攻击
      /// </summary>
      public static string IsValidSting(string strIn)
      {
         str = strIn.Replace("'","<@>1000");
         str = str.Replace(",","<@>1001");
         str = str.Replace("/"","<@>1002");
         str = str.Replace("UPDATE","<@>1003");
         str = str.Replace("update","<@>1004");
         str = str.Replace("DELETE","<@>1005");
         str = str.Replace("delete","<@>1006");
         str = str.Replace("SELECT","<@>1007");
         str = str.Replace("select","<@>1008");
         return str;
      }
      /// <summary>
      /// 常用还原字符
      /// </summary>
      public static string IsValidToSting(string strIn)
      {
         str = strIn.Replace("<@>1000","'");
         str = str.Replace("<@>1001",",");
         str = str.Replace("<@>1002","/"");
         str = str.Replace("<@>1003","UPDATE");
         str = str.Replace("<@>1004","update");
         str = str.Replace("<@>1005","DELETE");
         str = str.Replace("<@>1006","delete");
         str = str.Replace("<@>1007","SELECT");
         str = str.Replace("<@>1008","select");
         return str;
      }
      /// <summary>
      /// 有效密码检验
      /// </summary>
      public static bool IsValidPassword(string strIn)
      {
         if (strIn.Length<6 || strIn.Length>20)
         {
            return false;
         }
         else
         {
            return Regex.IsMatch(strIn, "^[A-Za-z0-9]+$");
         }
      }

      /// <summary>
      /// 有效电子邮件格式检验
      /// </summary>
      public static bool IsValidEmail(string strIn)
      {
         return Regex.IsMatch(strIn, @"^([/w-/.]+)@((/[[0-9]{1,3}/.[0-9]{1,3}/.[0-9]{1,3}/.)|(([/w-]+/.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(/]?)$");
      }
      /// <summary>
      /// 有效URL检验
      /// </summary>
      public static bool IsValidUrl(string strIn)
      {
         return Regex.IsMatch(strIn, @"^http://([/w-]+/.)+[/w-]+(/[/w- ./?%&=]*)?$");
      }
      /// <summary>
      /// 有效日期检验 如2005-9-2
      /// 基本上把闰年和2月等的情况都考虑进去了
      /// </summary>
      public static bool IsValidDate(string strIn)
      {
         return Regex.IsMatch(strIn, @"^((((1[6-9]|[2-9]/d)/d{2})-(0?[13578]|1[02])-(0?[1-9]|[12]/d|3[01]))|(((1[6-9]|[2-9]/d)/d{2})-(0?[13456789]|1[012])-(0?[1-9]|[12]/d|30))|(((1[6-9]|[2-9]/d)/d{2})-0?2-(0?[1-9]|1/d|2[0-8]))|(((1[6-9]|[2-9]/d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))-0?2-29-))$");
      }
      /// <summary>
      /// 有效长日期检验 如2005-9-2 13:20:37
      /// 基本上把闰年和2月等的情况都考虑进去了
      /// </summary>
      public static bool IsValidDateLong(string strIn)
      {
         return Regex.IsMatch(strIn, @"^((((1[6-9]|[2-9]/d)/d{2})-(0?[13578]|1[02])-(0?[1-9]|[12]/d|3[01]))|(((1[6-9]|[2-9]/d)/d{2})-(0?[13456789]|1[012])-(0?[1-9]|[12]/d|30))|(((1[6-9]|[2-9]/d)/d{2})-0?2-(0?[1-9]|1/d|2[0-8]))|(((1[6-9]|[2-9]/d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))-0?2-29-)) (20|21|22|23|[0-1]?/d):[0-5]?/d:[0-5]?/d$");
      }
      /// <summary>
      /// 有效身份证检验
      /// </summary>
      public static bool IsValidIDCard(string strIn)
      {
         return Regex.IsMatch(strIn,@"^(/d{18}|/d{15})+$");
      }
      /// <summary>
      /// 有效邮政编码检验
      /// </summary>
      public static bool IsValidPcode(string strIn)
      {
         return Regex.IsMatch(strIn,@"^(/d{6})+$");
      }
      /// <summary>
      /// 有效电话检验
      /// 如0599-1234567-0000 或 0599-1234567 等
      /// </summary>
      public static bool IsValidTel(string strIn)
      {
         return Regex.IsMatch(strIn,@"^(((/d{3}|/d{4})-(/d{7}|/d{8}))|((/d{3}|/d{4})-(/d{7}|/d{8})-(/d{4})))$");
      }    
      /// <summary>
      /// 有效整数检验
      /// </summary>
      public static bool IsValidInt(string strIn)
      {
         //[0-9]也可
         return Regex.IsMatch(strIn, "^(//d)+$");
      }
      /// <summary>
      /// 有效英文检验
      /// </summary>
      public static bool IsValidEnglish(string strIn)
      {
         return Regex.IsMatch(strIn, "^([A-Za-z])+$");
      }
      /// <summary>
      /// 有效中文检验
      /// </summary>
      public static bool IsValidChinese(string strIn)
      {
         return Regex.IsMatch(strIn, "^([/u4e00-/u9fa5])+$");
      }
      
      
      
      /// <summary>
      /// 有效英文-数字检验
      /// </summary>
      public static bool IsValidEnglishInt(string strIn)
      {
         //[A-Za-z|0-9]也可以
         return Regex.IsMatch(strIn, "^[A-Za-z0-9]+$");
      }
      /// <summary>
      /// 有效中文-数字检验
      /// </summary>
      public static bool IsValidChineseInt(string strIn)
      {
         return Regex.IsMatch(strIn, "^[0-9/u4e00-/u9fa5]+$");
      }
      /// <summary>
      /// 有效中文-英文-数字检验
      /// </summary>
      public static bool IsValidChineseEnglishInt(string strIn)
      {
         return Regex.IsMatch(strIn, "^[A-Za-z0-9/u4e00-/u9fa5]+$");
      }
/// <summary>
/// 显示成功信息
/// </summary>
/// <param name="SucMessage">成功提示信息</param>
/// <param name="type">类型,1 父窗口刷新;2 只显示成功信息;3 显示成功信息后 关闭当前窗口;4 刷新父窗口;</param>
/// <returns>返回string类型成功信息</returns>
public static string ShowSuc(string SucMessage,int type)
{
   string temp_str;
   switch(type)
   {
    case 1:
     temp_str = "<script>alert(/"" + SucMessage + "!/");window.parent.location.reload();</script>";
     break;
    case 2:
     temp_str = "<script>alert(/"" + SucMessage + "!/");</script>";
     break;
    case 3:
     temp_str = "<script>alert(/"" + SucMessage + "!/");window.close();</script>";
     break;
    case 4:
     temp_str ="<script>window.parent.location.reload();</script>";
     break;
    default:
     temp_str = "<script>alert(/"" + SucMessage + "!/");window.close();window.opener.location.reload();</script>";
     break;
   }
  
   return temp_str;
}

/// <summary>
/// 过滤非法字符
/// </summary>
/// <param name="strString">将要过滤的字符串</param>
/// <returns>返回过滤以后的字符</returns>
public static string FiltForbidStr(string strString)
{
   string tempstr="";
   tempstr=strString;
   if (tempstr!=null && tempstr!="")
   {
    tempstr = tempstr.Replace("'","''");
   }
   return tempstr;
}

/// <summary>
/// 过滤字符
/// </summary>
/// <param name="strString"></param>
/// <returns></returns>
public static string FiltRemoteForbidStr(string strString)
{
   string tempstr="";
   tempstr=strString;
   if (tempstr!=null && tempstr!="")
   {
    tempstr = tempstr.Replace("'","''");
    //tempstr = tempstr.Replace("|","");
    //tempstr = tempstr.Replace("[","");
    //tempstr = tempstr.Replace("(","");
    //tempstr = tempstr.Replace(";","");
    //tempstr = tempstr.Replace("%","");
    //tempstr = tempstr.Replace("-","");
    //tempstr = tempstr.Replace("=","");
    //tempstr = tempstr.Replace(".","");
   }
   return tempstr;
}

/// <summary>
/// 检测是否含有非法字符
/// </summary>
/// <param name="strString"></param>
/// <returns></returns>
public static bool CheckBidStr(string strString)
{
   bool outValue=false;
   if(strString!=null&&strString.Length>0)
   {
    string[] bidStrlist = new string[20];
    bidStrlist[0]="'";
    bidStrlist[1]=";";
    bidStrlist[2]=":";
    bidStrlist[3]="%";
    bidStrlist[4]="@";
    bidStrlist[5]="&";
    bidStrlist[6]="#";
    bidStrlist[7]="/"";
    bidStrlist[8]="net user";
    bidStrlist[9]="exec";
    bidStrlist[10]="net localgroup";
    bidStrlist[11]="select";
    bidStrlist[12]="asc";
    bidStrlist[13]="char";
    bidStrlist[14]="mid";
    bidStrlist[15]="insert";
    bidStrlist[16]="delete";
    bidStrlist[17]="drop";
    bidStrlist[18]="truncate";
    bidStrlist[19]="xp_cmdshell";

    string tempStr = strString.ToLower();
    for(int i=0;i<bidStrlist.Length;i++)
    {
     if(tempStr.IndexOf(bidStrlist[i])!=-1)
     {
      outValue=true;
      break;
     }
    }
   }
   return outValue;
}

/// <summary>
/// 取汉字的长度
/// </summary>
/// <param name="strString">原字符串</param>
/// <param name="strLen">取汉字个数</param>
/// <returns>截取后的字符串</returns>
public static string LeftTrue(string strString,int strLenth)
{
   if ( strString != null )
   {
    int i, c, t;
    char[] charArr = strString.ToCharArray();

    if( charArr.Length <= strLenth )
    {
     return strString;
    }
    else
    {
     t = 0;
     for( i = 0; i < charArr.Length; i++ )
     {
      c = charArr[i];
      if( c < 0 )
       c += 65536;
      if( c > 255 )
       t += 2;
      else
       t++;
      if( t > strLenth * 2 )
       break;
     }
     return new string( charArr, 0, i );
    }
   }
   else
   {
    return strString;
   }
}

/// <summary>
/// Hash编码
/// </summary>
/// <param name="strString">将要编码的字符串</param>
/// <param name="strFormat">编码格式(MD5或者SHA1)</param>
/// <returns></returns>
public static string EncryptStr(string strString, string strFormat)
{
   if (strString.Length!=0)
   {
    switch(strFormat.ToUpper())
    {
     case "SHA1":
      return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(strString,"SHA1");
     case "MD5":
      return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(strString,"MD5");
     default:
      return strString;
    }
   }
   else
   {
    return strString;
   }
}

/// <summary>
/// base64编码
/// </summary>
/// <param name="strString">将要编码的字符串</param>
/// <returns>编码后的字符串</returns>
public static string EnBase64(string strString)
{
   if (strString.Length!=0)
   {
    //System.Text.Encoding ens = System.Text.Encoding.GetEncoding(54936);
    return Convert.ToBase64String( System.Text.Encoding.UTF8.GetBytes(strString) );
   }
   return strString;
}

/// <summary>
/// base64解码
/// </summary>
/// <param name="strString">简要解码的字符串</param>
/// <returns>解码后的字符串</returns>
public static string DeBase64(string strString)
{
   if (strString.Length!=0)
   {
    //System.Text.Encoding ens = System.Text.Encoding.GetEncoding(54936);
    return System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(strString));
   }
   return strString;
}
/// <summary>
/// 格式化字符串
/// </summary>
/// <param name="strString">将要格式化的字符串</param>
/// <returns>格式化后的字符串</returns>
public static string KeepFormat(string strString)
{
   string str;
   str = strString;
   if(str!=null)
   {
    str = str.Replace(" ","");
    str = str.Replace("<br>","");
    str = str.Replace(Microsoft.VisualBasic.Strings.Chr(9).ToString(),"");
    str = str.Replace(Microsoft.VisualBasic.Strings.Chr(34).ToString(),"");
    str = str.Replace(Microsoft.VisualBasic.Strings.Chr(39).ToString(),"");
    str = str.Replace(Microsoft.VisualBasic.Strings.Chr(13).ToString()+Microsoft.VisualBasic.Strings.Chr(10).ToString(),"");
   }
   return str;
}
/// <summary>
/// 过滤字符串
/// </summary>
/// <param name="strString">将要过滤的字符串</param>
/// <returns>过滤后的字符串</returns>
public static string Keep(string strString)
{
   string str;
   str = strString;
   if(str!=null)
   {
    str = str.Replace("'","''");
    str = str.Replace(" ","&nbsp;");
    str = str.Replace("<","&lt");
    str = str.Replace(">","&gt");
    str = str.Replace("|","");
    str = str.Replace(Microsoft.VisualBasic.Strings.Chr(9).ToString(),"&nbsp;");
    str = str.Replace(Microsoft.VisualBasic.Strings.Chr(34).ToString(),"&quot;");
    str = str.Replace(Microsoft.VisualBasic.Strings.Chr(39).ToString(),"&#39;");
    str = str.Replace(Microsoft.VisualBasic.Strings.Chr(13).ToString()+Microsoft.VisualBasic.Strings.Chr(10).ToString(),"<br>");
    //str = str.Replace(Microsoft.VisualBasic.Strings.Chr(10).ToString(),"");
   }
   return str;
}

/// <summary>
/// 过滤js字符串
/// </summary>
/// <param name="strString">将要过滤js的字符串</param>
/// <returns>过滤js后的字符串</returns>
public static string Fixjs(string strString)
{
   string str;
   str = strString;
   if(str!=null)
   {
    str = str.Replace("//","////");
    str = str.Replace(((char)34).ToString(),"///"");
    str = str.Replace(((char)39).ToString(),"//'");
    str = str.Replace(((char)13).ToString(),"//n");
    str = str.Replace(((char)10).ToString(),"//r");
    str = str.Replace("'","&#39;");
   }
   return str;
}

public static string ToHtml(string str)
{
   str = str.Replace(">", "&gt;");
   str = str.Replace("<", "&lt;");
   str = str.Replace(" ", "&nbsp;");
   str = str.Replace("/"","&quot;");
   //str = str.Replace("", "&nbsp;");
   //str = str.Replace("", "&quot;");
   //str = str.Replace("", "&#39;");
   str = str.Replace("/n", "<br>");
   str = str.Replace("/n/r", "<br>");
   return str;
}

/// <summary>
/// 转换js字符串
/// </summary>
/// <param name="strString">将要转换js的字符串</param>
/// <returns>转换js后的字符串</returns>
public static string EnFixjs(string strString)
{
   string str;
   str = strString;
   if(str!=null)
   {
    str = str.Replace("////","//");
    str = str.Replace("///"",((char)34).ToString());
    str = str.Replace("//'",((char)39).ToString());
    str = str.Replace("//n",((char)13).ToString());
    str = str.Replace("//r",((char)10).ToString());
    str = str.Replace("&#39;","'");
   }
   return str;
}

/// <summary>
/// 判断汉字的长度
/// </summary>
/// <param name="strString">原字符串</param>
/// <param name="maxLenth">长度</param>
/// <returns>字符串长度</returns>
public static bool MaxLenth(string strString,int maxLenth)
{
   if(strString!=null)
   {
    if(strString.Length<=maxLenth/2)
    {
     return false;
    }
    else
    {
     int t,i,c;
     t = 0;
     for(i=0;i<strString.Length;i++)
     {
      c =Microsoft.VisualBasic.Strings.Asc(strString.Substring(i,1));
      if(c < 0)
      {
       t = t + 2;
      }
      else
      {
       t = t + 1;
      }
     }
     if(t > maxLenth)
     {
      return true;
     }
     else
     {
      return false;
     }
    }
   }
   return true;
}

原创粉丝点击