c#经典常用小函数

 

// Utils收集各种函数
public class Utils
{
     public static int GetStringLength(string str)
     {//计算字符串字节长度
         return Encoding.Default.GetBytes(str).Length;
     }
     /*
     public static string Trim(string str)
     {
         if (str.Substring(0, 1) == " ")
         {
             for (int i = 0; i < str.Length; i++)
             {
                 if (str.Substring(i, 1) == " ")
                 {
                     str = str.Remove(i, 1);
                 }
                 else
                 {
                     break;
                 }
             }

         }

         if (str.Substring((str.Length - 1), 1) == " ")
         {
             for (int i = (str.Length - 1); i >= 0; i--)
             {
                 if (str.Substring(i, 1) == " ")
                 {
                     str = str.Remove(i, 1);
                 }
                 else
                 {
                     break;
                 }
             }
         }
         return str;
     }*/
     public static string Trim(string str)   //去除前后空格
     {
         return new Regex("^ , "");
     }

     public static string Cut_str(string str, int len)
     {//截取指定长度字符
         int _a = 0;
         int _b = 0;
         string _s = "";
         for (int _i = 0; _i < str.Length; _i++)
         {
             _b += 1;
             if (new Regex("^[//u4E00-//u9FAF]+$").IsMatch(str.Substring(_i, 1)))
             {
                 _a += 2;
             }
             else
             {
                 _a++;
             }
             if (_a == len)
             {
                 _s = str.Substring(0, _b);
                 break;
             }
             else if (_a > len)
             {
                 _s = str.Substring(0, (_b - 1)) + ".";
                 break;
             }
         }
         return _s;
     }
     public static string Ubb(string str)
     {//ubb转换代码,.*虽然能匹配所有但是还要加上 ?贪婪模式 否则会出现点小问题
         str = Regex.Replace(str, "

//[b//](.*?)//[///b//]", "<b>$1</b>");
         str = Regex.Replace(str, "//[u//](.*?)//[///u//]", "<u>$1</u>");
         str = Regex.Replace(str, "//[i//](.*?)//[///i//]", "<i>$1</i>");
         str = Regex.Replace(str, "//[b//](.*?)//[///b//]", "<b>$1</b>");
         str = Regex.Replace(str, "//[img//](.*?)//[///img//]", "<img src=/"$1/"></img>");
         str = Regex.Replace(str, "//[url=(.*?)//](.*?)//[///url//]", "<a href=/"$1/">$2</a>");
         str = Regex.Replace(str, "//[align=(.*?)//](.*?)//[///align//]", "<div align=/"$1/">$2</div>");
         str = Regex.Replace(str, "//[face//](.*?)//[///face//]", "<img src=/"images/$1.gif/"></img>");
         return str;
     }
     public static int GetInArrayID(string str, string[] str_2, bool outb)
     {//在字符串数组中查找是否存在某字符串
         int _num = str_2.Length;
         if (outb)
         {//true区分大小写
             for (int _i = 0; _i < _num; _i++)
             {
                 if (str == str_2[_i])
                 {//这样比较区分大小写
                     return _i;
                 }
             }
         }
         else
         {
             for (int _i = 0; _i < _num; _i++)
             {
                 if (str.ToLower() == str_2[_i].ToLower())
                 {
                     return _i;
                 }
             }
         }
         return -1; //不存在返回-1
     }
     public static string MD5(string str)
     {//md5加密函数
         byte[] b = Encoding.Default.GetBytes(str);
         b = new MD5CryptoServiceProvider().ComputeHash(b);
         string ret = "";
         for (int i = 0; i < b.Length; i++)
             ret += b[i].ToString("x").PadLeft(2, '0');
         return ret;
     }
     public static void ServerAlert(string str,string url )
     {
         HttpContext.Current.Response.Write("<script language=/"javascript/">alert(/""+str+"/");");
         HttpContext.Current.Response.Write("window.location.href=/""+url+"/";");
         HttpContext.Current.Response.Write("</script>");
         HttpContext.Current.Response.End();
         //公用类中不能直接用Response.因为这时候不是页面,也就没有Response对象
         //而因该使用HTtpcontext类来显示
     }

     //------------读写Cookie值---------------
     public static void WriteCookie(string strName, string strValue)
     {//写Cookie值
         HttpCookie cookie = HttpContext.Current.Request.Cookies[strName];
         if (cookie == null)
         {
             cookie = new HttpCookie(strName);
         }
         cookie.Value = strValue;
         HttpContext.Current.Response.AppendCookie(cookie);

     }
     public static void WriteCookie(string strName, string strValue, int expires)
     {//写cookie值+1重载函数 加时间
         HttpCookie cookie = HttpContext.Current.Request.Cookies[strName];
         if (cookie == null)
         {
             cookie = new HttpCookie(strName);
         }
         cookie.Value = strValue;
         cookie.Expires = DateTime.Now.AddMinutes(expires);
         HttpContext.Current.Response.AppendCookie(cookie);

     }
     public static void WriteCookie(string strName, string strKeyName,String strKeyValue)
     {//写cookie值+1重载函数 加子键/值
         HttpCookie cookie = HttpContext.Current.Request.Cookies[strName];
         if (cookie == null)
         {
             cookie = new HttpCookie(strName);
         }
         cookie.Values[strKeyName] = strKeyValue;
         HttpContext.Current.Response.AppendCookie(cookie);

     }
     public static void WriteCookie(string strName, string strKeyName, String strKeyValue, int expires)
     {//写cookie值+2重载函数 加子键/值 过期时间分钟计算
         HttpCookie cookie = HttpContext.Current.Request.Cookies[strName];
         if (cookie == null)
         {
             cookie = new HttpCookie(strName);
         }
         cookie.Values[strKeyName] = strKeyValue;
         cookie.Expires = DateTime.Now.AddMinutes(expires);
         //这里过期时间能影响到所有该集合下所有子键的过期时间
         HttpContext.Current.Response.AppendCookie(cookie);
     }

     public static string GetCookie(string strName)
     {//读cookie值
         if (HttpContext.Current.Request.Cookies != null && HttpContext.Current.Request.Cookies[strName] != null)
         {
             return HttpContext.Current.Request.Cookies[strName].Value.ToString();
         }

         return "";
     }
     public static string GetCookie(string strName,string strKeyName)
     {//读cookie值+1重载,读取Cookie子键值
         if (HttpContext.Current.Request.Cookies != null && HttpContext.Current.Request.Cookies[strName] != null&& HttpContext.Current.Request.Cookies[strName].Values[strKeyName] != null)
         {
             return HttpContext.Current.Request.Cookies[strName].Values[strKeyName].ToString();
         }

         return "";
     }
     public static void setFile(string str)
     {
         //把一个值写如文件,调试用
         string strFile = @"E:/CandC++/c#/session事件/01.txt";//这是路径
         FileStream fs = new FileStream(strFile, FileMode.Append, FileAccess.Write);
         //这里Append是追加模式,但是只能写模式下用这个模式
         StreamWriter sw = new StreamWriter(fs);//创建一个写字符串的流
         sw.WriteLine(str);
         sw.Close();//关闭流写入磁盘文件
     }

     //------------字段验证函数----------------
     public static bool validateName(string str)
     {
         return new Regex("^[//u4E00-//u9FAF//w+]+$").IsMatch(str);
     }
     public static bool validateLoginName(string str)  
     {
         return new Regex("^[//w_]+$").IsMatch(str);
     }
     public static bool validateEmail(string str)  
     {
         return new Regex("^[//w_//-//.]+?@//w+?//-?//w*?//-?//w*?(//.//w+)+?$").IsMatch(str);
     }
     public static bool validateTel(string str)
     {
         return new Regex("(^();
     }
     public static bool IsNumber(string str)
     {//判断是否数字
         return new Regex("^[0-9]+?$").IsMatch(str);
     }
     //----------------Request操作类-------------------
     public static bool IsPost()
     {//判断是否是POST传输
         return HttpContext.Current.Request.HttpMethod.Equals("POST");
     }
     public static bool IsGet()
     {
         return HttpContext.Current.Request.HttpMethod.Equals("GET");
     }
     public static string GetFormString(string str)
     {//因为取不到值Form或Querystring为null赋给其他数据类型出错所以这里更改下
         if (HttpContext.Current.Request.Form[str] == null)
         {
             return "";
         }
         else
         {
             return HttpContext.Current.Request.Form[str].ToString();
         }

     }
     public static string GetQueryString(string str)
     {//获得查询字符串
         if (HttpContext.Current.Request.QueryString[str] == null)
         {
             return "";
         }
         else
         {
             return HttpContext.Current.Request.QueryString[str].ToString();
         }
     }
     public static string GetServerString(string str)
     {//获得服务器变量值
         if (HttpContext.Current.Request.ServerVariables[str] == null)
         {
             return "";
         }
         else
         {
             return HttpContext.Current.Request.ServerVariables[str].ToString();
         }
     }
     public static int GetInt(string strName, int defValue)
     {//根据不同类型返回整数
         string str = "";
         switch (defValue)
         {
             case 1:
                 if (Utils.GetFormString(strName) != "")
                 {
                     str=Utils.GetFormString(strName);
                 }
                 break;
             case 2:
                 if (Utils.GetQueryString(strName) != "")
                 {
                     str = Utils.GetQueryString(strName);
                 }
                 break;
             case 3:
                 if (Utils.GetServerString(strName) != "")
                 {
                     str = Utils.GetServerString(strName);
                 }
                 break;
             default:
                 break;

         }
         if (str == "")
         {
             return 0;
         }
         else
         {
             return Int32.Parse(str);
         }
     }
     public static string GetUrlReferrer()
     {//获取上一页的连接地址
         string str = "";
         try
         {
             str = HttpContext.Current.Request.UrlReferrer.ToString();
             //本页直接打开获取这个值就是一个异常,所以处理下
         }
         catch { }
         return str;  
     }
     public static string GetCurrentFullHost()
     {//获得主机和端口号
         HttpRequest request = HttpContext.Current.Request;
         if (!request.Url.IsDefaultPort)
         {
             return string.Format("{0}:{1}", request.Url.Host, request.Url.Port.ToString());
         }
         return request.Url.Host;
     }
     public static string GetHost()
     {//直接获得的主机头
         return HttpContext.Current.Request.Url.Host;
     }
     public static string GetRawUrl()
     {//获得当前请求的从虚拟目录开始的:URl如有查询字符串则也包括在内
         return HttpContext.Current.Request.RawUrl;
     }
     public static string GetUrl()
     {//获得当前请求从HTTp:// Url如有查询字符串,则也包括在内
         return HttpContext.Current.Request.Url.ToString();
     }
     public static string GetPageName()
     {//返回当前页名字
         string[] urlArr = HttpContext.Current.Request.Url.AbsolutePath.Split('/');
         //这里是 AbsolutePath是返回一个不到参数的URl路径,不过Split注意里面要用'/'字符,而不是双引号
         return urlArr[urlArr.Length - 1].ToLower();
     }
     public static int GetParamCount()
     {//返回表单参数的总个数,无则返回0
         return HttpContext.Current.Request.Form.Count + HttpContext.Current.Request.QueryString.Count;
         //两个参数加起来就好了
     }
     public static bool IsIP(string ip)
     {//判断是否为IP
         return Regex.IsMatch(ip, @"^((2[0-4]/d|25[0-5]|[01]?/d/d?)/.){3}(2[0-4]/d|25[0-5]|[01]?/d/d?)$");
     }
     public static string GetIP()
     {//获取ID地址
         string result = String.Empty;

         result = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
         if (null == result || result == String.Empty)
         {
             result = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
         }

         if (null == result || result == String.Empty)
         {
             result = HttpContext.Current.Request.UserHostAddress;
         }

         if (null == result || result == String.Empty || !Utils.IsIP(result))
         {
             return "0.0.0.0";
         }

         return result;

     }

 

//-------------时间函数---------------------------------------------    

public static string GetTime()

    {    

     return DateTime.Now.ToString("HH:mm:ss");    

}  

public static string GetDateTime()   

{     

    return DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");   

}   

public static string GetDateTime(int relativeday)    

{

//+1重载       

//返回增加了relativeday数的时间,当然也可以用 AddHours 增加小时了,还有分秒等等。。       

return DateTime.Now.AddDays(relativeday).ToString("yyyy-MM-dd HH:mm:ss");    

}

public static int GetTimeSpan(DateTime Dt_1, DateTime Dt_2)   

{//返回两个时间差,差为两数之间的总秒数      

   TimeSpan Dt_3 = Dt_1 - Dt_2;     

    int _day = Dt_3.Days;      

   int _hours = Dt_3.Hours;      

   int _minutes = Dt_3.Minutes;      

   int _seconds = Dt_3.Seconds;   

      return ((((((_day * 60) + _hours) * 60) + _minutes) * 60) + _seconds);  

   }    

public static DateTime GetDateTime(string str)   

{

//用字符串来创建时间对象      

   string[] strArray = Regex.Split(str, "|:");   

      int _num = 1;     

    int _year = 0, _month = 0, _day = 0, _hours = 0, _minutes = 0, _seconds = 0;       

for (int i = 0; i < strArray.Length; i++)      

   {       

      if (IsNumber(strArray[i]))       

      {         

        switch (_num)            

     {    

case 1:                         _year = Int16.Parse(strArray[i]);                         break;                   

case 2:                         _month = Int16.Parse(strArray[i]);                         break;            

case 3:                         _day = Int16.Parse(strArray[i]);        break;             

case 4:                         _hours = Int16.Parse(strArray[i]);                         break;             

case 5:                         _minutes = Int16.Parse(strArray[i]);                         break;             

case 6:                         _seconds = Int16.Parse(strArray[i]);                         break;                     default:                         break;         

        }         

        _num++;          

   }       

}  

       if (_num >= 6)

         {             //创建时间对象,否则就出错提示       

      return new DateTime(_year, _month, _day, _hours, _minutes, _seconds);      

        }      

   else       

{           

return new DateTime(1, 1, 1, 1, 1, 1);    

     }   

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值