十年河东,十年河西,莫欺少年穷

学无止境,精益求精

记录下字符串类库,方便今后查阅

主要包含了字符串解决,去除HTML,SQL注入攻击检测,IP地址处理,Cookies操作,根据身份证获取性别、姓名、年龄等等

代码如下:

using System;
using System.Collections.Generic;
using System.Web;
using System.Collections;
using System.Text;
using System.Text.RegularExpressions;
using System.Data;
using System.Drawing;
using ZXing;
using System.Xml; namespace Hplus.Common
{
public class CommonMethod
{
public static bool IsPhone(string Phone)
{
return System.Text.RegularExpressions.Regex.IsMatch(Phone, @"^[1]+[3,5,4,7,8]+\d{9}");
}
/// <summary>
/// 判断是否是汉字
/// </summary>
/// <param name="text"></param>
/// <returns></returns>
public static bool CheckStringChinese(string text)
{
bool res = false;
foreach (char t in text)
{
if ((int)t > )
res = true;
}
return res;
}
#region 截取字符长度 static string CutString(string str, int len)
/// <summary>
/// 截取字符长度
/// </summary>
/// <param name="str">被截取的字符串</param>
/// <param name="len">所截取的长度</param>
/// <returns>子字符串</returns>
public static string CutString(string str, int len)
{
if (str == null || str.Length == || len <= )
{
return string.Empty;
} int l = str.Length; #region 计算长度
int clen = ;
while (clen < len && clen < l)
{
//每遇到一个中文,则将目标长度减一。
if ((int)str[clen] > ) { len--; }
clen++;
}
#endregion if (clen < l)
{
return str.Substring(, clen) + "...";
}
else
{
return str;
}
} /// <summary>
/// //截取字符串中文 字母
/// </summary>
/// <param name="content">源字符串</param>
/// <param name="length">截取长度!</param>
/// <returns></returns>
public static string SubTrueString(object content, int length)
{
string strContent = NoHTML(content.ToString()); bool isConvert = false;
int splitLength = ;
int currLength = ;
int code = ;
int chfrom = Convert.ToInt32("4e00", ); //范围(0x4e00~0x9fff)转换成int(chfrom~chend)
int chend = Convert.ToInt32("9fff", );
for (int i = ; i < strContent.Length; i++)
{
code = Char.ConvertToUtf32(strContent, i);
if (code >= chfrom && code <= chend)
{
currLength += ; //中文
}
else
{
currLength += ;//非中文
}
splitLength = i + ;
if (currLength >= length)
{
isConvert = true;
break;
}
}
if (isConvert)
{
return strContent.Substring(, splitLength);
}
else
{
return strContent;
}
}
#endregion #region /*产生验证码*/ GetCode(int codeLength) /// <summary>
/// 生成一个1到10000000之间的正整数
/// </summary>
/// <returns></returns>
public static int GetNums()
{
int a = new Random().Next(, );
return a;
}
/// <summary>
/// 产生验证码
/// </summary>
/// <param name="codeLength">获取的验证码长度</param>
/// <returns>验证码</returns>
public static string GetCode(int codeLength)
{ string so = "1,2,3,4,5,6,7,8,9,0,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z";
string[] strArr = so.Split(',');
string code = "";
Random rand = new Random();
for (int i = ; i < codeLength; i++)
{
code += strArr[rand.Next(, strArr.Length)];
}
return code;
} /// <summary>
/// 获取一个随机字符串
/// </summary>
/// <param name="count"></param>
/// <returns></returns>
public static string GetRandomChar(int count)
{
string[] s = { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z",
"", "", "", "", "", "", "", "", "", "" }; StringBuilder sb = new StringBuilder();
Random ran = new Random();
for (int i = ; i < count; i++)
{
int temp = ran.Next(s.Length);
sb.Append(s[temp]);
}
return sb.ToString();
} /// <summary>
/// 获取特定位数的随机数
/// </summary>
/// <param name="count"></param>
/// <returns></returns>
public static string GetRandomNums(int count)
{
StringBuilder sb = new StringBuilder();
sb.Append('', count - );
int min = int.Parse(sb.ToString()) + ;//最小值
sb.Append();
int max = int.Parse(sb.ToString());//最大值 Random ran = new Random();
return ran.Next(min, max).ToString();
} /// <summary>
/// //获取18位订单编号
/// </summary>
/// <returns></returns>
public static string GetOrderNum()
{
Random ran = new Random();
int random = ran.Next();//四位随机数
string dateStr = DateTime.Now.ToString("yyyyMMddhhmmss");
return "order" + dateStr + CovertIntToString(random, );
} /// <summary>
/// 获取支付编号
/// </summary>
/// <returns></returns>
public static string GetPayNum()
{
Random ran = new Random();
int random1 = ran.Next();//四位随机数
string dateStr = DateTime.Now.ToString("yyyyMMddhhmmss");
int random2 = ran.Next();//四位随机数
return CovertIntToString(random1, ) + dateStr + CovertIntToString(random2, );
}
public static string GetShopNum()
{
Random ran = new Random();
int random = ran.Next();//四位随机数
string dateStr = DateTime.Now.ToString("yyyyMMddhhmmss");
return "shop-" + dateStr + CovertIntToString(random, );
}
/// <summary>
/// //获取17位活动编号
/// </summary>
/// <returns></returns>
public static string GetHuoDongNum()
{
Random ran = new Random();
int random = ran.Next();//四位随机数
string dateStr = DateTime.Now.ToString("yyyyMMddhhmmss");
return "ACT" + dateStr + CovertIntToString(random, );
}
/// <summary>
/// //获取购物车产品流水号
/// </summary>
/// <returns></returns>
public static string GetCartNum()
{
Random ran = new Random();
int random = ran.Next();//四位随机数
string dateStr = DateTime.Now.ToString("yyyyMMddhhmmss");
return "ddpcart" + dateStr + CovertIntToString(random, );
} /// <summary>
/// //获取会员唯一编号
/// </summary>
/// <returns></returns>
public static string GetVIPNum()
{
Random ran = new Random();
int random = ran.Next();//四位随机数
string dateStr = DateTime.Now.ToString("yyyyMMddhhmmss");
return "VIP" + dateStr + CovertIntToString(random, );
} /// <summary>
/// 长度不够补0
/// </summary>
/// <param name="src"></param>
/// <param name="num"></param>
/// <returns></returns>
public static string CovertIntToString(object src, int num)
{
StringBuilder sb = new StringBuilder();
sb.Append('', num);
string sTarget = sb.ToString() + src.ToString(); return sTarget.Substring(sTarget.Length - num, num);
} private static double EARTH_RADIUS = 6378137.0;
/// <summary>
/// 获取地球两点之间的距离
/// </summary>
/// <param name="lat_a"></param>
/// <param name="lng_a"></param>
/// <param name="lat_b"></param>
/// <param name="lng_b"></param>
/// <returns></returns>
public static double Gps2m(double lat_a, double lng_a, double lat_b, double lng_b)
{ double radLat1 = (lat_a * Math.PI / 180.0);
double radLat2 = (lat_b * Math.PI / 180.0);
double a = radLat1 - radLat2;
double b = (lng_a - lng_b) * Math.PI / 180.0;
double s = * Math.Asin(Math.Sqrt(Math.Pow(Math.Sin(a / ), )
+ Math.Cos(radLat1) * Math.Cos(radLat2)
* Math.Pow(Math.Sin(b / ), )));
s = s * EARTH_RADIUS;
s = Math.Round(s * ) / ;
return s;
}
#endregion #region sql注入攻击
public static string[] words = { "select", "insert", "delete", "count(", "drop table", "update", "truncate", "asc(", "mid(", "char(", "xp_cmdshell", "exec", "master", "net", "and", "or", "where" }; public static string CheckParam(string Value)
{
Value = Value.Replace("'", "");
Value = Value.Replace(";", "");
Value = Value.Replace("--", "");
Value = Value.Replace("/**/", "");
return Value;
}
public static string CheckParamThrow(string Value)
{
for (int i = ; i < words.Length; i++)
{
if (Value.IndexOf(words[i], StringComparison.OrdinalIgnoreCase) > )
{
string pattern = string.Format(@"[\W]{0}[\W]", words[i]);
Regex rx = new Regex(pattern, RegexOptions.IgnoreCase);
if (rx.IsMatch(Value))
throw new Exception("发现sql注入痕迹!");
}
}
return CheckParam(Value);
}
/// <summary>
/// 查找是否含有非法参数
/// </summary>
/// <param name="Value"></param>
/// <returns></returns>
public static bool CheckParamBool(string Value)
{
for (int i = ; i < words.Length; i++)
{
if (Value.IndexOf(words[i], StringComparison.OrdinalIgnoreCase) > )
return true;
}
return false;
}
#endregion #region IP地址处理
/// <summary>
/// 取得客户端真实IP。如果有代理则取第一个非内网地址
/// by flower.b
/// </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(".") == -) //没有“.”肯定是非IPv4格式
result = null;
else
{
if (result.IndexOf(",") != -)
{
//有“,”,估计多个代理。取第一个不是内网的IP。
result = result.Replace(" ", "").Replace("'", "");
string[] temparyip = result.Split(",;".ToCharArray());
for (int i = ; i < temparyip.Length; i++)
{
if (IsIPAddress(temparyip[i])
&& temparyip[i].Substring(, ) != "10."
&& temparyip[i].Substring(, ) != "192.168"
&& temparyip[i].Substring(, ) != "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;
}
} /// <summary>
/// 判断是否是IP地址格式 0.0.0.0
/// </summary>
/// <param name="str1">待判断的IP地址</param>
/// <returns>true or false</returns>
private static bool IsIPAddress(string str1)
{
if (str1 == null || str1 == string.Empty || str1.Length < || str1.Length > ) return false; string regformat = @"^d{1,3}[.]d{1,3}[.]d{1,3}[.]d{1,3}$"; Regex regex = new Regex(regformat, RegexOptions.IgnoreCase);
return regex.IsMatch(str1);
}
#endregion #region HTML处理
/// <summary>
/// 将html标签转化为特殊字符type=0或特殊字符转化为HTML type=1
/// </summary>
/// <param name="vv">源字符串</param>
/// <param name="type">转化方式</param>
/// <returns></returns>
public static string HTML_Trans(string vv,int type)
{
if (type == )
{
vv = vv.Replace(" ", "&nbsp;");
vv = vv.Replace(" ", "&nbsp;");
vv = vv.Replace(">", "&gt;");
vv = vv.Replace("<", "&lt;");
vv = vv.Replace("&", "&amp;");
vv = vv.Replace("\"", "&quot;");
vv = vv.Replace("'", "&apos");
}
if (type == )
{
vv = vv.Replace("&nbsp;"," ");
vv = vv.Replace("&nbsp;"," ");
vv = vv.Replace("&gt;",">");
vv = vv.Replace("&lt;", "<");
vv = vv.Replace("&amp;","&");
vv = vv.Replace("&quot;","\"");
vv = vv.Replace("&apos", "'");
} return vv;
} /// <summary>
/// 去掉非法html标签
/// </summary>
/// <param name="Htmlstring"></param>
/// <returns></returns>
public static string NoHTML(object html)
{
if (html == null)
return "";
string Htmlstring = html.ToString();
//删除脚本
Htmlstring = Regex.Replace(Htmlstring, @"<script[^>]*?>.*?</script>", "", RegexOptions.IgnoreCase);
//删除HTML
Htmlstring = Regex.Replace(Htmlstring, @"<(.[^>]*)>", "", RegexOptions.IgnoreCase);
Htmlstring = Regex.Replace(Htmlstring, @"([\r\n])[\s]+", "", RegexOptions.IgnoreCase);
Htmlstring = Regex.Replace(Htmlstring, @"-->", "", RegexOptions.IgnoreCase);
Htmlstring = Regex.Replace(Htmlstring, @"<!--.*", "", RegexOptions.IgnoreCase); Htmlstring = Regex.Replace(Htmlstring, @"&(quot|#34);", "\"", RegexOptions.IgnoreCase);
Htmlstring = Regex.Replace(Htmlstring, @"&(amp|#38);", "&", RegexOptions.IgnoreCase);
Htmlstring = Regex.Replace(Htmlstring, @"&(lt|#60);", "<", RegexOptions.IgnoreCase);
Htmlstring = Regex.Replace(Htmlstring, @"&(gt|#62);", ">", RegexOptions.IgnoreCase);
Htmlstring = Regex.Replace(Htmlstring, @"&(nbsp|#160);", " ", RegexOptions.IgnoreCase);
Htmlstring = Regex.Replace(Htmlstring, @"&(iexcl|#161);", "\xa1", RegexOptions.IgnoreCase);
Htmlstring = Regex.Replace(Htmlstring, @"&(cent|#162);", "\xa2", RegexOptions.IgnoreCase);
Htmlstring = Regex.Replace(Htmlstring, @"&(pound|#163);", "\xa3", RegexOptions.IgnoreCase);
Htmlstring = Regex.Replace(Htmlstring, @"&(copy|#169);", "\xa9", RegexOptions.IgnoreCase);
Htmlstring = Regex.Replace(Htmlstring, @"&#(\d+);", "", RegexOptions.IgnoreCase); Htmlstring.Replace("<", "");
Htmlstring.Replace(">", "");
Htmlstring.Replace("\r\n", "");
return Htmlstring.Trim();
} #endregion #region cookie操作
/// <summary>
/// Cookies赋值
/// </summary>
/// <param name="strName">主键</param>
/// <param name="strValue">键值</param>
/// <param name="strDay">有效天数</param>
/// <returns></returns>
public static bool setCookieForMIn(string strName, string strValue, int Mintius)
{
try
{
HttpCookie Cookie = new HttpCookie(strName);
//Cookie.Domain = ".xxx.com";//当要跨域名访问的时候,给cookie指定域名即可,格式为.xxx.com
Cookie.Expires = DateTime.Now.AddMinutes(Mintius);
Cookie.Value = strValue;
System.Web.HttpContext.Current.Response.Cookies.Add(Cookie);
return true;
}
catch
{
return false;
}
} /// <summary>
/// Cookies赋值
/// </summary>
/// <param name="strName">主键</param>
/// <param name="strValue">键值</param>
/// <param name="strDay">有效天数</param>
/// <returns></returns>
public static bool setCookie(string strName, string strValue, int strDay)
{
try
{
HttpCookie Cookie = new HttpCookie(strName);
//Cookie.Domain = ".xxx.com";//当要跨域名访问的时候,给cookie指定域名即可,格式为.xxx.com
Cookie.Expires = DateTime.Now.AddDays(strDay);
Cookie.Value = strValue;
System.Web.HttpContext.Current.Response.Cookies.Add(Cookie);
return true;
}
catch
{
return false;
}
} /// <summary>
/// 读取Cookies
/// </summary>
/// <param name="strName">主键</param>
/// <returns></returns> public static string getCookie(string strName)
{
HttpCookie Cookie = System.Web.HttpContext.Current.Request.Cookies[strName];
if (Cookie != null)
{
return Cookie.Value.ToString();
}
else
{
return null;
}
} /// <summary>
/// 删除Cookies
/// </summary>
/// <param name="strName">主键</param>
/// <returns></returns>
public static bool delCookie(string strName)
{
try
{
HttpCookie Cookie = new HttpCookie(strName);
//Cookie.Domain = ".xxx.com";//当要跨域名访问的时候,给cookie指定域名即可,格式为.xxx.com
Cookie.Expires = DateTime.Now.AddDays(-);
System.Web.HttpContext.Current.Response.Cookies.Add(Cookie);
return true;
}
catch
{
return false;
}
}
#endregion #region 获取当天的最大时间 和 最小时间
/// <summary>
/// 获取当天的最大时间 和 最小时间
/// </summary>
/// <param name="ty">0:默认为最小时间 1:最大时间</param>
/// <returns></returns>
public static string getMaxMinTim(int ty = )
{
if (ty == )
{
return DateTime.Now.Year + "-" + DateTime.Now.Month + "-" + DateTime.Now.Day + " 00:00:00";
}
else
{
return DateTime.Now.Year + "-" + DateTime.Now.Month + "-" + DateTime.Now.Day + " 23:59:59";
}
}
#endregion #region 根据身份证 获取年龄 性别
public static PersonForIdCard GetPersonByIdCard(string identityCard)
{
string birthday = string.Empty;
string sex = string.Empty;
if (identityCard.Length == )//处理18位的身份证号码从号码中得到生日和性别代码
{
birthday = identityCard.Substring(, ) + "-" + identityCard.Substring(, ) + "-" + identityCard.Substring(, );
sex = identityCard.Substring(, );
}
if (identityCard.Length == )
{
birthday = "" + identityCard.Substring(, ) + "-" + identityCard.Substring(, ) + "-" + identityCard.Substring(, );
sex = identityCard.Substring(, );
}
int UserAge = DateTime.Now.Year - Convert.ToDateTime(birthday).Year;
if (int.Parse(sex) % == )
{
sex = "女";
}
else
{
sex = "男";
}
PersonForIdCard P = new PersonForIdCard
{
Age = UserAge,
Sex = sex,
Birthday = birthday
};
return P;
}
#endregion public static int GetAgeByDate(DateTime? birthDay)
{
int age = ;
if (birthDay.HasValue)
{
age = DateTime.Now.Year - birthDay.Value.Year;
if (DateTime.Now.Month < birthDay.Value.Month || (DateTime.Now.Month == birthDay.Value.Month && DateTime.Now.Day < birthDay.Value.Day)) age--;
if (age <= )
{
return ;
}
return age;
}
return age;
}
} public class PersonForIdCard
{
public int Age { get; set; }
public string Sex { get; set; }
public string Birthday { get; set; }
}
}

Aes可逆加密如下:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks; namespace Hplus.Common
{
public class AesSecurity
{
/// <summary>
/// AES加密
/// </summary>
/// <param name="str">待加密字符串</param>
/// <param name="AES_KEY">公钥</param>
/// <returns>加密后字符串</returns>
public static string AesEncrypt(string str, string AES_KEY)
{
try
{
string key = AES_KEY;
//分组加密算法
AesCryptoServiceProvider aes = new AesCryptoServiceProvider();
byte[] inputByteArray = Encoding.UTF8.GetBytes(str);//得到需要加密的字节数组
//设置密钥及密钥向量
aes.Key = Encoding.UTF8.GetBytes(key);
//aes.IV = Encoding.UTF8.GetBytes(key);
aes.Mode = CipherMode.ECB;
aes.Padding = PaddingMode.PKCS7;
byte[] cipherBytes = null;
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, aes.CreateEncryptor(), CryptoStreamMode.Write))
{
cs.Write(inputByteArray, , inputByteArray.Length);
cs.FlushFinalBlock();
cipherBytes = ms.ToArray();//得到加密后的字节数组
cs.Close();
ms.Close();
}
}
return Convert.ToBase64String(cipherBytes);
}
catch { }
return string.Empty;
} /// <summary>
/// AES解密
/// </summary>
/// <param name="str">待解密字符串</param>
/// <param name="AES_KEY">公钥</param>
/// <returns>解密后字符串</returns>
public static string AesDecrypt(string str, string AES_KEY)
{
try
{
string key = AES_KEY;
byte[] cipherText = Convert.FromBase64String(str);
AesCryptoServiceProvider aes = new AesCryptoServiceProvider();
aes.Key = Encoding.UTF8.GetBytes(key);
//aes.IV = Encoding.UTF8.GetBytes(key);
aes.Mode = CipherMode.ECB;
aes.Padding = PaddingMode.PKCS7;
byte[] decryptBytes = new byte[cipherText.Length];
using (MemoryStream ms = new MemoryStream(cipherText))
{
using (CryptoStream cs = new CryptoStream(ms, aes.CreateDecryptor(), CryptoStreamMode.Read))
{
cs.Read(decryptBytes, , decryptBytes.Length);
cs.Close();
ms.Close();
}
}
return Encoding.UTF8.GetString(decryptBytes).Replace("\0", ""); //将字符串后尾的'\0'去掉
}
catch { }
return string.Empty;
}
}
}

缓存操作

using System;
using System.Web;
using System.Collections;
using System.Web.Caching; namespace Hplus.Common
{
public class CacheHelper
{
/// <summary>
/// 获取数据缓存
/// </summary>
/// <param name="CacheKey">键</param>
public static object GetCache(string CacheKey)
{
System.Web.Caching.Cache objCache = HttpRuntime.Cache;
return objCache[CacheKey];
} /// <summary>
/// 设置数据缓存
/// </summary>
public static void SetCache(string CacheKey, object objObject)
{
System.Web.Caching.Cache objCache = HttpRuntime.Cache;
objCache.Insert(CacheKey, objObject);
} /// <summary>
/// 设置数据缓存
/// </summary>
public static void SetCache(string CacheKey, object objObject, TimeSpan Timeout)
{
System.Web.Caching.Cache objCache = HttpRuntime.Cache;
objCache.Insert(CacheKey, objObject, null, DateTime.MaxValue, Timeout, System.Web.Caching.CacheItemPriority.NotRemovable, null);
} /// <summary>
/// 设置数据缓存
/// </summary>
public static void SetCache(string CacheKey, object objObject, DateTime absoluteExpiration, TimeSpan slidingExpiration)
{
System.Web.Caching.Cache objCache = HttpRuntime.Cache;
objCache.Insert(CacheKey, objObject, null, absoluteExpiration, slidingExpiration);
} /// <summary>
/// 移除指定数据缓存
/// </summary>
public static void RemoveAllCache(string CacheKey)
{
System.Web.Caching.Cache _cache = HttpRuntime.Cache;
_cache.Remove(CacheKey);
} /// <summary>
/// 移除全部缓存
/// </summary>
public static void RemoveAllCache()
{
System.Web.Caching.Cache _cache = HttpRuntime.Cache;
IDictionaryEnumerator CacheEnum = _cache.GetEnumerator();
while (CacheEnum.MoveNext())
{
_cache.Remove(CacheEnum.Key.ToString());
}
} //另外的一个缓存类库
/// <summary>
/// 创建缓存项的文件
/// </summary>
/// <param name="key">缓存Key</param>
/// <param name="obj">object对象</param>
public static void Insert(string key, object obj)
{
//创建缓存
HttpContext.Current.Cache.Insert(key, obj);
}
/// <summary>
/// 移除缓存项的文件
/// </summary>
/// <param name="key">缓存Key</param>
public static void Remove(string key)
{
//创建缓存
HttpContext.Current.Cache.Remove(key);
}
/// <summary>
/// 创建缓存项的文件依赖
/// </summary>
/// <param name="key">缓存Key</param>
/// <param name="obj">object对象</param>
/// <param name="fileName">文件绝对路径</param>
public static void Insert(string key, object obj, string fileName)
{
//创建缓存依赖项
CacheDependency dep = new CacheDependency(fileName);
//创建缓存
HttpContext.Current.Cache.Insert(key, obj, dep);
} /// <summary>
/// 创建缓存项过期
/// </summary>
/// <param name="key">缓存Key</param>
/// <param name="obj">object对象</param>
/// <param name="expires">过期时间(分钟)</param>
public static void Insert(string key, object obj, int expires)
{
HttpContext.Current.Cache.Insert(key, obj, null, Cache.NoAbsoluteExpiration, new TimeSpan(, expires, ));
} /// <summary>
/// 获取缓存对象
/// </summary>
/// <param name="key">缓存Key</param>
/// <returns>object对象</returns>
public static object Get(string key)
{
if (string.IsNullOrEmpty(key))
{
return null;
}
return HttpContext.Current.Cache.Get(key);
} /// <summary>
/// 获取缓存对象
/// </summary>
/// <typeparam name="T">T对象</typeparam>
/// <param name="key">缓存Key</param>
/// <returns></returns>
public static T Get<T>(string key)
{
object obj = Get(key);
return obj == null ? default(T) : (T)obj;
}
}
}

汉字拼音

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web; namespace Hplus.Common
{
public class FirstCode
{
/// <summary> /// 在指定的字符串列表CnStr中检索符合拼音索引字符串 /// </summary> /// <param name="CnStr">汉字字符串</param> /// <returns>相对应的汉语拼音首字母串</returns> public static string GetSpellCode(string CnStr)
{ string strTemp = ""; int iLen = CnStr.Length; int i = ; for (i = ; i <= iLen - ; i++)
{ strTemp += GetCharSpellCode(CnStr.Substring(i, ));
} return strTemp; } /// <summary>
/// 获取首字符字母
/// </summary>
/// <param name="CnStr"></param>
/// <returns></returns>
public static string GetFirstSpellCode(string CnStr)
{ string strTemp = ""; int iLen = CnStr.Length; int i = ; for (i = ; i <= iLen - ; i++)
{ strTemp += GetCharSpellCode(CnStr.Substring(i, ));
break;
} return strTemp; } /// <summary> /// 得到一个汉字的拼音第一个字母,如果是一个英文字母则直接返回大写字母 /// </summary> /// <param name="CnChar">单个汉字</param> /// <returns>单个大写字母</returns> private static string GetCharSpellCode(string CnChar)
{ long iCnChar; byte[] ZW = System.Text.Encoding.Default.GetBytes(CnChar); //如果是字母,则直接返回首字母 if (ZW.Length == )
{ return CommonMethod.CutString(CnChar.ToUpper(), ); }
else
{ // get the array of byte from the single char int i1 = (short)(ZW[]); int i2 = (short)(ZW[]); iCnChar = i1 * + i2; } // iCnChar match the constant if ((iCnChar >= ) && (iCnChar <= ))
{ return "A"; } else if ((iCnChar >= ) && (iCnChar <= ))
{ return "B"; }
else if ((iCnChar >= ) && (iCnChar <= ))
{ return "C"; }
else if ((iCnChar >= ) && (iCnChar <= ))
{ return "D"; }
else if ((iCnChar >= ) && (iCnChar <= ))
{ return "E"; }
else if ((iCnChar >= ) && (iCnChar <= ))
{ return "F"; }
else if ((iCnChar >= ) && (iCnChar <= ))
{ return "G"; }
else if ((iCnChar >= ) && (iCnChar <= ))
{ return "H"; }
else if ((iCnChar >= ) && (iCnChar <= ))
{ return "J"; }
else if ((iCnChar >= ) && (iCnChar <= ))
{ return "K"; }
else if ((iCnChar >= ) && (iCnChar <= ))
{ return "L"; }
else if ((iCnChar >= ) && (iCnChar <= ))
{ return "M"; }
else if ((iCnChar >= ) && (iCnChar <= ))
{ return "N"; }
else if ((iCnChar >= ) && (iCnChar <= ))
{ return "O"; }
else if ((iCnChar >= ) && (iCnChar <= ))
{ return "P"; }
else if ((iCnChar >= ) && (iCnChar <= ))
{ return "Q"; }
else if ((iCnChar >= ) && (iCnChar <= ))
{ return "R"; }
else if ((iCnChar >= ) && (iCnChar <= ))
{ return "S"; }
else if ((iCnChar >= ) && (iCnChar <= ))
{ return "T"; }
else if ((iCnChar >= ) && (iCnChar <= ))
{ return "W"; }
else if ((iCnChar >= ) && (iCnChar <= ))
{ return "X"; }
else if ((iCnChar >= ) && (iCnChar <= ))
{ return "Y"; }
else if ((iCnChar >= ) && (iCnChar <= ))
{ return "Z"; }
else return ("?"); }
}
}

如果想详细了解汉字拼音及首字母的处理,请参考博客:C# 获取社会统一信用代码 和 C# 获取汉字拼音首字母/全拼

@天才卧龙的博客

C# 常用类库(字符串处理,汉字首字母拼音,注入攻击,缓存操作,Cookies操作,AES加密等)的更多相关文章

  1. JS实现获取汉字首字母拼音、全拼音及混拼音的方法

    本文实例讲述了JS实现获取汉字首字母拼音.全拼音及混拼音的方法.分享给大家供大家参考,具体如下: 这里需要用到一个js获取汉字拼音的插件,可点击此处本站下载. 运行效果如下: 完整示例代码: ? 1 ...

  2. 【PHP原生】获取字符串所有汉字首字母和首个汉字首字母

    1.废话不多说,看代码,获取字符串汉字首字母,兼容GBK和UTF-8 <?php //获取单个汉字拼音首字母.注意:此处不要纠结.汉字拼音是没有以U和V开头的 function getfirst ...

  3. c#获取汉字首字母拼音

    /* * 由SharpDevelop创建. * 用户: lenovo * 日期: 2013/10/22 * 时间: 20:15 * * 要改变这种模板请点击 工具|选项|代码编写|编辑标准头文件 */ ...

  4. JS获取汉字首字母

    //获取 汉字首字母 function makePy(str) { if (typeof (str) != "string") throw new Error(-1, " ...

  5. PHP获取汉字首字母并分组排序

    <?php /** * 错误状态码定义 * User: xiucai * Date: 2018/3/11 * Time: 12:23 */ namespace extend; class Wor ...

  6. mysql和SqlServer 中取得汉字字段的各汉字首字母

    mysql 中取得汉字字段的各汉字首字母 这个转载于http://blog.csdn.net/lky5387/article/details/11973721 DELIMITER ;;CREATE  ...

  7. python获取汉字首字母

    获取汉字首字母 关注公众号"轻松学编程"了解更多. 应用场景之一:可用于获取名字首字母,在数据库中查询记录时,可以用它来排序输出. from pytz import unicode ...

  8. 获取汉字首字母并分组排列 PHP

    1.代码class Character{ /** * 数组根据首首字母排序 */ /** * 二维数组根据首字母分组排序 * @param array $data 二维数组 * @param stri ...

  9. SQL SERVER 得到汉字首字母函数四版全集 --【叶子】

    --创建取汉字首字母函数(第三版) create function [dbo].[f_getpy_V3] ( ) ) ) as begin ),) ,@len = len(@col),@sql = ' ...

随机推荐

  1. 第三方库Mantle的简单实用

    1. 测试时, 可以使用下面这个网址及代码来测试, 里面有模型,数组,以及字典, 还可以有long long 转NSDate,  string 转 int等. NSURL *url = [NSURLU ...

  2. 基于file上传文件的并发上传(多个文件一起上传到后台并把数据存储的同一条数据中,如 数据库字段videopath,imge。前台发送来的文件file1,file2。 videopath=file1,imge=file2)

    前台代码: <div class="tab-content"> <dl> <dt>所属栏目</dt> <dd> < ...

  3. Android自定义注解

    1.元注解   概念:用来定义其他注解的注解,自定义注解的时候,需要使用它来定义我们的注解.   在jdk 1.5之后提供了 java.lang.annotation 来支持注解功能   常见的四种元 ...

  4. Linux下环境变量(.bash_profile和.bashrc的区别)

    在linux系统下,如果下载并安装了应用程序,在启动时很有可能在键入它的名称时出现"command not found"的提示内容.如果每次都到安装目标文件夹内,找到可执行文件来进 ...

  5. Windows | Ubuntu18.04分别安装Matlab 2017b破解版

    首先下载好Windows和Ubuntu 版本的MATLAB 2017b 安装包, 1.Windows上安装,解压文件R2017b_win64_dvd1.iso和R2017b_win64_dvd2.is ...

  6. fiddler面试题

    1.什么叫断点? Break Point:进行接口测试时,为了测试后端功能而设置的. 2.断点有哪些方式? Before Requests:在请求时,没有达到服务器之前设置断点.     -- 全局断 ...

  7. jmeter连接不上MySQL数据库的原因以及解决方法

    1.Cannot create PoolableConnectionFactory (Client does not support authentication protocol requested ...

  8. 剑指Offer-19.顺时针打印矩阵(C++/Java)

    题目: 输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下4 X 4矩阵: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 则依次打印出数字 ...

  9. BZOJ4027/LG4107 「HEOI2015」兔子与樱花 树形DP+贪心

    问题描述 LG4107 题解 首先,我们可以直接令结点 \(x\) 的权值为 \(c[x]+son_x\) ,发现将 \(x,y\) 合并,相当于增加 \(c[x]+c[y]-1\) 的重量. 容易想 ...

  10. Eclipse GitHub SSH2 key配置

    1. 用Eclipse自带git插件进行配置我们的用户名和密码,即是自己github注册用户. 2.windows -- perferences--General--Network Commectio ...