開發項目中常用的一些方法,我整理出一個工具類。每次開發一個新的項目,我們在搭建項目框架的時候,都會用到一些類,比如我們會常用的工具類,主要是包含一些常用的方法。 比如一些對象的轉換(對象轉換為string,int,double等,),分割字符串結尾的逗號,截取字符串,情況html標簽,對象加密,生成隨機碼,根據日期生成訂單號等等。在這裡我共享一個我寫的工具類,希望在以後的開發中能為大家利用上。
public class Utils
{
#region 系統版本
///
public class VersionInfo
{
public int FileMajorPart
{
get { return 2; }
}
public int FileMinorPart
{
get { return 0; }
}
public int FileBuildPart
{
get { return 0; }
}
public string ProductName
{
get { return "DTcms"; }
}
public int ProductType
{
get { return 0; }
}
}
public static string GetVersion()
{
return DTKeys.ASSEMBLY_VERSION;
}
#endregion
#region 對象轉換處理
///
/// ///
public static bool IsNumeric(object expression)
{
if (expression != null)
return IsNumeric(expression.ToString());
return false;
}
///
/// ///
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;
}
///
/// ///
public static bool IsDouble(object expression)
{
if (expression != null)
return Regex.IsMatch(expression.ToString(), @"^([0-9])[0-9]*(/./w*)?$");
return false;
}
///
/// 字符串 ///
public static string[] GetStrArray(string str)
{
return str.Split(new char[',']);
}
///
/// List /// 分隔符 ///
public static string GetArrayStr(List
{
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();
}
///
/// 要轉換的字符串 /// 缺省值 ///
public static bool StrToBool(object expression, bool defValue)
{
if (expression != null)
return StrToBool(expression, defValue);
return defValue;
}
///
/// 要轉換的字符串 /// 缺省值 ///
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;
}
///
/// 要轉換的字符串 /// 缺省值 ///
public static int ObjToInt(object expression, int defValue)
{
if (expression != null)
return StrToInt(expression.ToString(), defValue);
return defValue;
}
///
/// 要轉換的字符串 /// 缺省值 ///
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));
}
///
/// 要轉換的字符串 /// 缺省值 ///
public static decimal ObjToDecimal(object expression, decimal defValue)
{
if (expression != null)
return StrToDecimal(expression.ToString(), defValue);
return defValue;
}
///
/// 要轉換的字符串 /// 缺省值 ///
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;
}
///
/// 要轉換的字符串 /// 缺省值 ///
public static float ObjToFloat(object expression, float defValue)
{
if (expression != null)
return StrToFloat(expression.ToString(), defValue);
return defValue;
}
///
/// 要轉換的字符串 /// 缺省值 ///
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;
}
///
/// 要轉換的字符串 /// 缺省值 ///
public static DateTime StrToDateTime(string str, DateTime defValue)
{
if (!string.IsNullOrEmpty(str))
{
DateTime dateTime;
if (DateTime.TryParse(str, out dateTime))
return dateTime;
}
return defValue;
}
///
/// 要轉換的字符串 ///
public static DateTime StrToDateTime(string str)
{
return StrToDateTime(str, DateTime.Now);
}
///
/// 要轉換的對象 ///
public static DateTime ObjectToDateTime(object obj)
{
return StrToDateTime(obj.ToString());
}
///
/// 要轉換的對象 /// 缺省值 ///
public static DateTime ObjectToDateTime(object obj, DateTime defValue)
{
return StrToDateTime(obj.ToString(), defValue);
}
///
/// 要轉換的對象 ///
public static string ObjectToStr(object obj)
{
if (obj == null)
return "";
return obj.ToString().Trim();
}
#endregion
#region 分割字符串
///
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] { };
}
///
///
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 刪除最後結尾的一個逗號
///
public static string DelLastComma(string str)
{
return str.Substring(0, str.LastIndexOf(","));
}
#endregion
#region 刪除最後結尾的指定字符後的字符
///
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 生成指定長度的字符串
///
/// 生成的長度 /// 以str生成字符串 ///
public static string StringOfChar(int strLong, string str)
{
string ReturnStr = "";
for (int i = 0; i < strLong; i++)
{
ReturnStr += str;
}
return ReturnStr;
}
#endregion
#region 生成日期隨機碼
///
///
public static string GetRamCode()
{
#region
return DateTime.Now.ToString("yyyyMMddHHmmssffff");
#endregion
}
#endregion
#region 生成隨機字母或數字
///
/// 生成長度 ///
public static string Number(int Length)
{
return Number(Length, false);
}
///
/// 生成長度 /// 是否要在生成前將當前線程阻止以避免重復 ///
public static string Number(int Length, bool Sleep)
{
if (Sleep)
System.Threading.Thread.Sleep(3);
string result = "";
System.Random random = new Random();
for (int i = 0; i < Length; i++)
{
result += random.Next(10).ToString();
}
return result;
}
///
/// 待生成的位數 public static string GetCheckCode(int codeCount)
{
string str = string.Empty;
int rep = 0;
long num2 = DateTime.Now.Ticks + rep;
rep++;
Random random = new Random(((int)(((ulong)num2) & 0xffffffffL)) | ((int)(num2 >> rep)));
for (int i = 0; i < codeCount; i++)
{
char ch;
int num = random.Next();
if ((num % 2) == 0)
{
ch = (char)(0x30 + ((ushort)(num % 10)));
}
else
{
ch = (char)(0x41 + ((ushort)(num % 0x1a)));
}
str = str + ch.ToString();
}
return str;
}
///
///
public static string GetOrderNumber()
{
string num = DateTime.Now.ToString("yyMMddHHmmss");//yyyyMMddHHmmssms
return num + Number(2).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 截取字符長度
///
/// 字符 /// 長度 ///
public static string CutString(string inputString, int len)
{
if (string.IsNullOrEmpty(inputString))
return "";
inputString = DropHTML(inputString);
ASCIIEncoding ascii = new ASCIIEncoding();
int tempLen = 0;
string tempString = "";
byte[] s = ascii.GetBytes(inputString);
for (int i = 0; i < s.Length; i++)
{
if ((int)s[i] == 63)
{
tempLen += 2;
}
else
{
tempLen += 1;
}
try
{
tempString += inputString.Substring(i, 1);
}
catch
{
break;
}
if (tempLen > len)
break;
}
//如果截過則加上半個省略號
byte[] mybyte = System.Text.Encoding.Default.GetBytes(inputString);
if (mybyte.Length > len)
tempString += "…";
return tempString;
}
#endregion
#region 清除HTML標記
public static string DropHTML(string Htmlstring)
{
if (string.IsNullOrEmpty(Htmlstring)) return "";
//刪除腳本
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, @"