C#tools
程序员文章站
2022-05-04 11:07:42
public class Utils { #region 对象转换处理 /// /// 判断对象是否为Int32类型的数字 /// /// /// p ......
public class utils { #region 对象转换处理 /// <summary> /// 判断对象是否为int32类型的数字 /// </summary> /// <param name="expression"></param> /// <returns></returns> public static bool isnumeric(object expression) { if (expression != null) return isnumeric(expression.tostring()); return false; } /// <summary> /// 判断对象是否为int32类型的数字 /// </summary> /// <param name="expression"></param> /// <returns></returns> public static bool isnumeric(string expression) { if (expression != null) { string str = expression; if (str.length > 0 && str.length <= 11 && regex.ismatch(str, @"^[-]?[0-9]*[.]?[0-9]*$")) { if ((str.length < 10) || (str.length == 10 && str[0] == '1') || (str.length == 11 && str[0] == '-' && str[1] == '1')) return true; } } return false; } /// <summary> /// 截取字符串长度,超出部分使用后缀suffix代替,比如abcdevfddd取前3位,后面使用...代替 /// </summary> /// <param name="orginstr"></param> /// <param name="length"></param> /// <param name="suffix"></param> /// <returns></returns> public static string substraddsuffix(string orginstr, int length, string suffix) { string ret = orginstr; if (orginstr.length > length) { ret = orginstr.substring(0, length) + suffix; } return ret; } /// <summary> /// 是否为double类型 /// </summary> /// <param name="expression"></param> /// <returns></returns> public static bool isdouble(object expression) { if (expression != null) return regex.ismatch(expression.tostring(), @"^([0-9])[0-9]*(\.\w*)?$"); return false; } /// <summary> /// 检测是否符合email格式 /// </summary> /// <param name="stremail">要判断的email字符串</param> /// <returns>判断结果</returns> public static bool isvalidemail(string stremail) { return regex.ismatch(stremail, @"^[\w\.]+([-]\w+)*@[a-za-z0-9-_]+[\.][a-za-z0-9-_]"); } public static bool isvaliddoemail(string stremail) { return regex.ismatch(stremail, @"^@((\[[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> /// <param name="strurl">要验证的url</param> /// <returns>判断结果</returns> public static bool isurl(string strurl) { return regex.ismatch(strurl, @"^(http|https)\://([a-za-z0-9\.\-]+(\:[a-za-z0-9\.&%\$\-]+)*@)*((25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])|localhost|([a-za-z0-9\-]+\.)*[a-za-z0-9\-]+\.(com|edu|gov|int|mil|net|org|biz|arpa|info|name|pro|aero|coop|museum|[a-za-z]{1,10}))(\:[0-9]+)*(/($|[a-za-z0-9\.\,\?\'\\\+&%\$#\=~_\-]+))*$"); } /// <summary> /// 将字符串转换为数组 /// </summary> /// <param name="str">字符串</param> /// <returns>字符串数组</returns> public static string[] getstrarray(string str) { return str.split(new char[',']); } /// <summary> /// 将数组转换为字符串 /// </summary> /// <param name="list">list</param> /// <param name="speater">分隔符</param> /// <returns>string</returns> public static string getarraystr(list<string> list, string speater) { stringbuilder sb = new stringbuilder(); for (int i = 0; i < list.count; i++) { if (i == list.count - 1) { sb.append(list[i]); } else { sb.append(list[i]); sb.append(speater); } } return sb.tostring(); } /// <summary> /// object型转换为bool型 /// </summary> /// <param name="strvalue">要转换的字符串</param> /// <param name="defvalue">缺省值</param> /// <returns>转换后的bool类型结果</returns> public static bool strtobool(object expression, bool defvalue) { if (expression != null) return strtobool(expression, defvalue); return defvalue; } /// <summary> /// string型转换为bool型 /// </summary> /// <param name="strvalue">要转换的字符串</param> /// <param name="defvalue">缺省值</param> /// <returns>转换后的bool类型结果</returns> public static bool strtobool(string expression, bool defvalue) { if (expression != null) { if (string.compare(expression, "true", true) == 0) return true; else if (string.compare(expression, "false", true) == 0) return false; } return defvalue; } /// <summary> /// 将对象转换为int32类型 /// </summary> /// <param name="expression">要转换的字符串</param> /// <param name="defvalue">缺省值</param> /// <returns>转换后的int类型结果</returns> public static int objtoint(object expression, int defvalue) { if (expression != null) return strtoint(expression.tostring(), defvalue); return defvalue; } /// <summary> /// 将字符串转换为int32类型 /// </summary> /// <param name="expression">要转换的字符串</param> /// <param name="defvalue">缺省值</param> /// <returns>转换后的int类型结果</returns> public static int strtoint(string expression, int defvalue) { if (string.isnullorempty(expression) || expression.trim().length >= 11 || !regex.ismatch(expression.trim(), @"^([-]|[0-9])[0-9]*(\.\w*)?$")) return defvalue; int rv; if (int32.tryparse(expression, out rv)) return rv; return convert.toint32(strtofloat(expression, defvalue)); } /// <summary> /// object型转换为decimal型 /// </summary> /// <param name="strvalue">要转换的字符串</param> /// <param name="defvalue">缺省值</param> /// <returns>转换后的decimal类型结果</returns> public static decimal objtodecimal(object expression, decimal defvalue) { if (expression != null) return strtodecimal(expression.tostring(), defvalue); return defvalue; } /// <summary> /// string型转换为decimal型 /// </summary> /// <param name="strvalue">要转换的字符串</param> /// <param name="defvalue">缺省值</param> /// <returns>转换后的decimal类型结果</returns> public static decimal strtodecimal(string expression, decimal defvalue) { if ((expression == null) || (expression.length > 10)) return defvalue; decimal intvalue = defvalue; if (expression != null) { bool isdecimal = regex.ismatch(expression, @"^([-]|[0-9])[0-9]*(\.\w*)?$"); if (isdecimal) decimal.tryparse(expression, out intvalue); } return intvalue; } /// <summary> /// object型转换为float型 /// </summary> /// <param name="strvalue">要转换的字符串</param> /// <param name="defvalue">缺省值</param> /// <returns>转换后的int类型结果</returns> public static float objtofloat(object expression, float defvalue) { if (expression != null) return strtofloat(expression.tostring(), defvalue); return defvalue; } /// <summary> /// string型转换为float型 /// </summary> /// <param name="strvalue">要转换的字符串</param> /// <param name="defvalue">缺省值</param> /// <returns>转换后的int类型结果</returns> public static float strtofloat(string expression, float defvalue) { if ((expression == null) || (expression.length > 10)) return defvalue; float intvalue = defvalue; if (expression != null) { bool isfloat = regex.ismatch(expression, @"^([-]|[0-9])[0-9]*(\.\w*)?$"); if (isfloat) float.tryparse(expression, out intvalue); } return intvalue; } /// <summary> /// 将对象转换为日期时间类型 /// </summary> /// <param name="str">要转换的字符串</param> /// <param name="defvalue">缺省值</param> /// <returns>转换后的int类型结果</returns> public static datetime strtodatetime(string str, datetime defvalue) { if (!string.isnullorempty(str)) { datetime datetime; if (datetime.tryparse(str, out datetime)) return datetime; } return defvalue; } /// <summary> /// 将对象转换为日期时间类型 /// </summary> /// <param name="str">要转换的字符串</param> /// <returns>转换后的int类型结果</returns> public static datetime strtodatetime(string str) { return strtodatetime(str, datetime.now); } /// <summary> /// 将对象转换为日期时间类型 /// </summary> /// <param name="obj">要转换的对象</param> /// <returns>转换后的int类型结果</returns> public static datetime objecttodatetime(object obj) { return strtodatetime(obj.tostring()); } /// <summary> /// 将对象转换为日期时间类型 /// </summary> /// <param name="obj">要转换的对象</param> /// <param name="defvalue">缺省值</param> /// <returns>转换后的int类型结果</returns> public static datetime objecttodatetime(object obj, datetime defvalue) { return strtodatetime(obj.tostring(), defvalue); } /// <summary> /// 将对象转换为字符串 /// </summary> /// <param name="obj">要转换的对象</param> /// <returns>转换后的string类型结果</returns> public static string objecttostr(object obj) { if (obj == null) return ""; return obj.tostring().trim(); } /// <summary> /// 将对象转换为int类型 /// </summary> /// <param name="o"></param> /// <returns></returns> public static int objtoint(object obj) { if (isnumber(obj)) { return int.parse(obj.tostring()); } else { return 0; } } /// <summary> /// 判断对象是否可以转成int型 /// </summary> /// <param name="o"></param> /// <returns></returns> public static bool isnumber(object o) { int tmpint; if (o == null) { return false; } if (o.tostring().trim().length == 0) { return false; } if (!int.tryparse(o.tostring(), out tmpint)) { return false; } else { return true; } } #endregion #region 分割字符串 /// <summary> /// 分割字符串 /// </summary> public static string[] splitstring(string strcontent, string strsplit) { if (!string.isnullorempty(strcontent)) { if (strcontent.indexof(strsplit) < 0) return new string[] { strcontent }; return regex.split(strcontent, regex.escape(strsplit), regexoptions.ignorecase); } else return new string[0] { }; } /// <summary> /// 分割字符串 /// </summary> /// <returns></returns> public static string[] splitstring(string strcontent, string strsplit, int count) { string[] result = new string[count]; string[] splited = splitstring(strcontent, strsplit); for (int i = 0; i < count; i++) { if (i < splited.length) result[i] = splited[i]; else result[i] = string.empty; } return result; } #endregion #region 删除最后结尾的一个逗号 /// <summary> /// 删除最后结尾的一个逗号 /// </summary> public static string dellastcomma(string str) { if (str.length < 1) { return ""; } return str.substring(0, str.lastindexof(",")); } #endregion #region 删除最后结尾的指定字符后的字符 /// <summary> /// 删除最后结尾的指定字符后的字符 /// </summary> public static string dellastchar(string str, string strchar) { if (string.isnullorempty(str)) return ""; if (str.lastindexof(strchar) >= 0 && str.lastindexof(strchar) == str.length - 1) { return str.substring(0, str.lastindexof(strchar)); } return str; } #endregion #region 生成指定长度的字符串 /// <summary> /// 生成指定长度的字符串,即生成strlong个str字符串 /// </summary> /// <param name="strlong">生成的长度</param> /// <param name="str">以str生成字符串</param> /// <returns></returns> public static string stringofchar(int strlong, string str) { string returnstr = ""; for (int i = 0; i < strlong; i++) { returnstr += str; } return returnstr; } #endregion #region 生成日期随机码 /// <summary> /// 生成日期随机码 /// </summary> /// <returns></returns> public static string getramcode() { #region return datetime.now.tostring("yyyymmddhhmmssffff"); #endregion } #endregion #region 生成随机字母或数字 /// <summary> /// 生成随机数字 /// </summary> /// <param name="length">生成长度</param> /// <returns></returns> public static string number(int length) { return number(length, false); } /// <summary> /// 生成随机数字 /// </summary> /// <param name="length">生成长度</param> /// <param name="sleep">是否要在生成前将当前线程阻止以避免重复</param> /// <returns></returns> public static string number(int length, bool sleep) { if (sleep) system.threading.thread.sleep(3); string result = ""; system.random random = new system.random(); for (int i = 0; i < length; i++) { result += random.next(10).tostring(); } return result; } /// <summary> /// 根据日期和随机码生成订单号 /// </summary> /// <returns></returns> public static string getordernumber() { string num = datetime.now.tostring("yymmddhhmmss");//yyyymmddhhmmssms return num + number(2, true).tostring(); } private static int next(int numseeds, int length) { byte[] buffer = new byte[length]; system.security.cryptography.rngcryptoserviceprovider gen = new system.security.cryptography.rngcryptoserviceprovider(); gen.getbytes(buffer); uint randomresult = 0x0;//这里用uint作为生成的随机数 for (int i = 0; i < length; i++) { randomresult |= ((uint)buffer[i] << ((length - 1 - i) * 8)); } return (int)(randomresult % numseeds); } #endregion #region txt代码转换成html格式 /// <summary> /// 字符串字符处理 /// </summary> /// <param name="chr">等待处理的字符串</param> /// <returns>处理后的字符串</returns> /// //把txt代码转换成html格式 public static string tohtml(string input) { stringbuilder sb = new stringbuilder(input); sb.replace("'", "'"); sb.replace("&", "&"); sb.replace("<", "<"); sb.replace(">", ">"); sb.replace("\r\n", "<br />"); sb.replace("\n", "<br />"); sb.replace("\t", " "); //sb.replace(" ", " "); return sb.tostring(); } #endregion #region html代码转换成txt格式 /// <summary> /// 字符串字符处理 /// </summary> /// <param name="chr">等待处理的字符串</param> /// <returns>处理后的字符串</returns> /// //把html代码转换成txt格式 public static string totxt(string input) { stringbuilder sb = new stringbuilder(input); sb.replace(" ", " "); sb.replace("<br>", "\r\n"); sb.replace("<br>", "\n"); sb.replace("<br />", "\n"); sb.replace("<br />", "\r\n"); sb.replace("<", "<"); sb.replace(">", ">"); sb.replace("&", "&"); return sb.tostring(); } #endregion #region 检测是否有sql危险字符 /// <summary> /// 检测是否有sql危险字符 /// </summary> /// <param name="str">要判断字符串</param> /// <returns>判断结果</returns> public static bool issafesqlstring(string str) { return !regex.ismatch(str, @"[-|;|,|\/|\(|\)|\[|\]|\}|\{|%|@|\*|!|\']"); } /// <summary> /// 检查危险字符 /// </summary> /// <param name="input"></param> /// <returns></returns> public static string filter(string sinput) { if (sinput == null || sinput == "") return null; string sinput1 = sinput.tolower(); string output = sinput; string pattern = @"*|and|exec|insert|select|delete|update|count|master|truncate|declare|char(|mid(|chr(|'"; if (regex.match(sinput1, regex.escape(pattern), regexoptions.compiled | regexoptions.ignorecase).success) { throw new exception("字符串中含有非法字符!"); } else { output = output.replace("'", "''"); } return output; } /// <summary> /// 检查过滤设定的危险字符 /// </summary> /// <param name="intext">要过滤的字符串 </param> /// <returns>如果参数存在不安全字符,则返回true </returns> public static bool sqlfilter(string word, string intext) { if (intext == null) return false; foreach (string i in word.split('|')) { if ((intext.tolower().indexof(i + " ") > -1) || (intext.tolower().indexof(" " + i) > -1)) { return true; } } return false; } #endregion #region 过滤特殊字符 /// <summary> /// 过滤特殊字符 /// </summary> /// <param name="input"></param> /// <returns></returns> public static string htmls(string input) { if (input != string.empty && input != null) { string ihtml = input.tolower(); ihtml = ihtml.replace("<script", "<script"); ihtml = ihtml.replace("script>", "script>"); ihtml = ihtml.replace("<%", "<%"); ihtml = ihtml.replace("%>", "%>"); ihtml = ihtml.replace("<$", "<$"); ihtml = ihtml.replace("$>", "$>"); ihtml = ihtml.replace("'", "'"); ihtml = ihtml.replace("\"", """); ihtml = ihtml.replace("<", "<"); ihtml = ihtml = ihtml.replace(">", ">"); ihtml = ihtml.replace("\r", "\\\r"); ihtml = ihtml.replace("\n", "\\\n"); ihtml = ihtml.replace("\t", " "); return ihtml; } else { return string.empty; } } #endregion #region 检查是否为ip地址 /// <summary> /// 是否为ip /// </summary> /// <param name="ip"></param> /// <returns></returns> public static bool isip(string 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?)$"); } #endregion #region 替换指定的字符串 /// <summary> /// 替换指定的字符串 /// </summary> /// <param name="originalstr">原字符串</param> /// <param name="oldstr">旧字符串</param> /// <param name="newstr">新字符串</param> /// <returns></returns> public static string replacestr(string originalstr, string oldstr, string newstr) { if (string.isnullorempty(oldstr)) { return ""; } return originalstr.replace(oldstr, newstr); } #endregion #region dats转换城datetime /// <summary> /// 替换指定的dats转换城datetime /// </summary> /// <param name="datsstr">原字符串</param> /// <returns></returns> public static datetime replacedats(string datsstr) { datetime datstime = datetime.minvalue; if (!string.isnullorempty(datsstr)) { if (datsstr.trim().length == 8) { string year = datsstr.remove(4); string month = datsstr.substring(4).remove(2); string day = datsstr.substring(4).substring(2); datstime = new datetime(int.parse(year), int.parse(month), int.parse(day)); } } return datstime; } /// <summary> /// 获取枚举的特性 /// </summary> /// <param name="t"></param> /// <returns></returns> public static string displayenum(enum t) { var t_type = t.gettype(); var fieldname = enum.getname(t_type, t); var attributes = t_type.getfield(fieldname).getcustomattributes(false); var enumdisplayattribute = attributes.firstordefault(p => p.gettype().equals(typeof(displayattribute))) as displayattribute; return enumdisplayattribute == null ? fieldname : enumdisplayattribute.display; } /// <summary> /// 根据特性获取枚举 /// </summary> /// <param name="t"></param> /// <returns></returns> public static object displayenum<t>(string code) { var t_type = typeof(t); var field = enum.getvalues(typeof(t)).oftype<t>().tolist(); var attributes = t_type.getfields().select(x => new { attr = x.getcustomattributes(false).firstordefault(y=>y.gettype().equals(typeof(displayattribute))) as displayattribute, enu = x }).where(x=>x.attr !=null); var enumvalue = attributes.where(x => x.attr.display == code).firstordefault(); if (enumvalue != null) { return enum.parse(t_type, enumvalue.enu.name); } return null; } #endregion #region 获取guid /// <summary> /// 获取32位的guid /// </summary> /// <returns></returns> public static string getguid() { return guid.newguid().tostring().replace("-", "").toupper(); } /// <summary> /// 获取36位的guid /// </summary> /// <returns></returns> public static string getguidlong() { return guid.newguid().tostring().toupper(); } #endregion }
上一篇: 远离无声世界,解决声卡故障
下一篇: 反对超频的10大理由