工作总结:常用的C#方法(部分来源于网络收藏)
//// <summary>
/// 转全角的函数(SBC case)
/// </summary>
/// <param name="input">任意字符串</param>
/// <returns>全角字符串</returns>
///<remarks>
///全角空格为12288,半角空格为32
///其他字符半角(33-126)与全角(65281-65374)的对应关系是:均相差65248
///</remarks>
public static string ToSDC(string input)
{
//半角转全角:
char[] c = input.ToCharArray();
for (int i = 0; i < c.Length; i++)
{
if (c[i] == 32)
{
c[i] = (char)12288;
continue;
}
if (c[i] < 127)
c[i] = (char)(c[i] + 65248);
}
return new string(c);
}
/// <summary>
/// 转半角的函数(DBC case)
/// </summary>
/// <param name="input">任意字符串</param>
/// <returns>半角字符串</returns>
///<remarks>
///全角空格为12288,半角空格为32
///其他字符半角(33-126)与全角(65281-65374)的对应关系是:均相差65248
///</remarks>
public static string ToDSC(string input)
{
char[] c = input.ToCharArray();
for (int i = 0; i < c.Length; i++)
{
if (c[i] == 12288)
{
c[i] = (char)32;
continue;
}
if (c[i] > 65280 && c[i] < 65375)
c[i] = (char)(c[i] - 65248);
}
return new string(c);
}
/// <summary>
/// 是否是数字
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static bool IsNumeric(string str)
{
if (str == null || str.Length == 0)
return false;
System.Text.ASCIIEncoding ascii = new System.Text.ASCIIEncoding();
byte[] bytestr = ascii.GetBytes(str);
foreach (byte c in bytestr)
{
if (c < 48 || c > 57)
{
return false;
}
}
return true;
}
public static bool IsNum(String str)
{
for (int i = 1; i < str.Length; i++)
{
if (!Char.IsNumber(str, i))
return false;
}
return true;
}
/// <summary>
/// 判断字符或字符串里是否有汉字
/// </summary>
/// <param name="CString"></param>
/// <returns></returns>
public static bool IsChina(string CString)
{
bool BoolValue = false;
for (int i = 0; i < CString.Length; i++)
{
if (Convert.ToInt32(Convert.ToChar(CString.Substring(i, 1))) < Convert.ToInt32(Convert.ToChar(128)))
{
BoolValue = false;
}
else
{
BoolValue = true;
}
}
return BoolValue;
}
public static string CutString(string str, int length)
{
string newString = "";
if (str != "")
{
if (str.Length > length)
{
newString = str.Substring(0, length) + "...";
}
else
{
newString = str;
}
}
return newString;
}
#region 日期格式化
/// <summary>格式化显示日期方法</summary>
public static string GetFormatDateByDate(DateTime datetime)
{
string tmpDate = datetime.ToShortDateString();
return CommonHelper.GetFormatDateByText(tmpDate);
}
/// <summary>格式化显示日期方法</summary>
public static string GetFormatDateByText(string datetime)
{
if (string.IsNullOrEmpty(datetime))
return string.Empty;
/* 注意:
* 数据库中为Null的日期值,在经过Gentle转换后会处理成
* .Net系统中的DateTime.MinValue,也就是"0001-1-1 0:00:00"
* 因此这里在处理日期值时,将"0001-1-1 0:00:00"处理成
* system.Empty,用于页面显示
*/
string minDate = "0001";
string maxDate = "9999";
int min = datetime.IndexOf(minDate);
int max = datetime.IndexOf(maxDate);
if (min>-1 || max>-1)//如果匹配"0001"或"9999",则返回空字符串
return string.Empty;
/*
* 替换一下日期分隔符号
* "-","-",".","/","/","。","",""
*/
string str = datetime;
if (str.IndexOf("-") > 0)
str = str.Replace("-", ".");
else if(str.IndexOf("/")>0)
str = str.Replace("/", ".");
else if (str.IndexOf(".") > 0)
str = str.Replace(".", ".");
else if (str.IndexOf("/") > 0)
str = str.Replace("/", ".");
else if (str.IndexOf("-") > 0)
str = str.Replace("-", ".");
else if (str.IndexOf("。") > 0)
str = str.Replace("。", ".");
return str;
}
/// <summary>获得实际日期(用于保存数据)</summary>
public static DateTime GetRealDateTimeByText(string datetime)
{
string str = datetime;
if (str.IndexOf(".") > 0)
str = str.Replace(".", "/");
else if (str.IndexOf("-") > 0)
str = str.Replace("-", "/");
else if (str.IndexOf(".") > 0)
str = str.Replace(".", "/");
else if (str.IndexOf("/") > 0)
str = str.Replace("/", "/");
else if (str.IndexOf("-") > 0)
str = str.Replace("-", "/");
else if (str.IndexOf("。") > 0)
str = str.Replace("。", "/");
else if (str.IndexOf(".") > 0)
str = str.Replace(".", "/");
try
{
return DateTime.Parse(str);
}
catch
{
return new DateTime();
//throw new Exception("日期格式错误,转换失败!"+ex.Message);
}
}
/// <summary>获得实际日期(用于保存数据)</summary>
/// 注意:专用于转换"2000年1月28日"格式的方法
public static DateTime GetRealDateTimeByYYYYMMDD(string datetime)
{
string str = datetime.Replace("年", ".").Replace("月", ".").Replace("日", "");
return CommonHelper.GetRealDateTimeByText(str);
}
#endregion
#region MD5加密字符串
/// <summary>加密字符串方法byMD5</summary>
/// <param name="password">要加密的字符串</param>
/// <returns>已加密的字符串</returns>
public static string EncryptByMD5(string password)
{
string encryptPwd = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(password, "md5");
return encryptPwd.ToLower();
//一下代码为未补位加密结果
//MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
//byte[] result = md5.ComputeHash(System.Text.Encoding.Default.GetBytes(password));
//string str2 = "";
//for (int i = 0; i < result.Length; i++)
//{
// str2 += string.Format("{0:x}", result[i]);
//}
//return str2.ToLower();
}
#endregion
#region 动态生成GUID
//动态生成GUID
public static string GetNewGuid()
{
return System.Guid.NewGuid().ToString().Replace("-", "").ToUpper();
}
#endregion
#region 判断是否是数字(正整数)
/// <summary>
/// 根据传入字符串判断是否是数字(正整数)
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static bool IsNumeric(string str)
{
System.Text.RegularExpressions.Regex reg1
= new System.Text.RegularExpressions.Regex(@"^\d*$");
return reg1.IsMatch(str);
}
#endregion
#region 根据传入字符串判断是否是数字(金额数字)
/// <summary>
/// 根据传入字符串判断是否是数字(金额数字)
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static bool IsMoney(string str)
{
System.Text.RegularExpressions.Regex reg1
= new System.Text.RegularExpressions.Regex(@"^[-]?\d*[.]?\d*$");
return reg1.IsMatch(str);
}
#endregion
#region 根据传入出生日期字符串判断当前年龄
/// <summary>
/// 根据传入出生日期字符串判断当前年龄
/// </summary>
/// <param name="birthday"></param>
/// <returns></returns>
public static int GetAge(DateTime birthday)
{
int year = System.DateTime.Now.Year;
int month = System.DateTime.Now.Month;
int day = System.DateTime.Now.Day;
int year1 = birthday.Year;
int month1 = birthday.Month;
int day1 = birthday.Day;
int Age = year + month / 12 + day / 365 - year1 - month1 / 12 - day1 / 365;
return Age;
}
#endregion
#region 返回固定长度的字符串
/// <summary>
/// 返回固定长度的字符串
/// </summary>
/// <param name="s"></param>
/// <param name="l"></param>
/// <returns></returns>
public static string getStr(string s, int l)
{
string temp = s;
if (Regex.Replace(temp, "[\u4e00-\u9fa5]", "zz", RegexOptions.IgnoreCase).Length <= l)
{
return temp;
}
for (int i = temp.Length; i >= 0; i--)
{
temp = temp.Substring(0, i);
if (Regex.Replace(temp, "[\u4e00-\u9fa5]", "zz", RegexOptions.IgnoreCase).Length <= l - 3)
{
return temp + "";
}
}
return "";
}
/// <summary>
/// 截取指定长度中英文字符串方
/// </summary>
/// <param name="stringToSub"></param>
/// <param name="length"></param>
/// <returns></returns>
public static string GetFirstString(string stringToSub, int length)
{
Regex regex = new Regex("[\u4e00-\u9fa5]+", RegexOptions.Compiled);
char[] stringChar = stringToSub.ToCharArray();
StringBuilder sb = new StringBuilder();
int nLength = 0;
bool isCut = false;
for (int i = 0; i < stringChar.Length; i++)
{
if (regex.IsMatch((stringChar[i]).ToString()))
{
sb.Append(stringChar[i]);
nLength += 2;
}
else
{
sb.Append(stringChar[i]);
nLength = nLength + 1;
}
if (nLength > length)
{
isCut = true;
break;
}
}
if (isCut)
return sb.ToString() + "..";
else
return sb.ToString();
}
/// <summary>
/// 截取固定字符串
/// </summary>
/// <param name="inputString">待截取的字符串</param>
/// <param name="len">指定长度</param>
/// <returns>固定长度len的字符串</returns>
public static string CutString(string inputString, int len)
{
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;
}
/// <summary>
/// 截取指定长度字符串(含盖半全角问题)
/// </summary>
/// <param name="content"></param>
/// <param name="length"></param>
/// <returns></returns>
private static string getLeftSubString(string content, int length)
{
Encoding encoding = Encoding.GetEncoding("gb2312");
StringBuilder sb = new StringBuilder();
int totalLength = 0;
foreach (char contentChar in content)
{
int size = encoding.GetByteCount(new char[] { contentChar });
if (totalLength + size > length - 2)
{
sb.Append("..");
break;
}
sb.Append(contentChar);
totalLength += size;
}
return sb.ToString();
}
#endregion
///// <summary>
///// 根据输入的字符串进行身份证合法性验证
///// </summary>
///// <param name="CardNumber"></param>
///// <returns></returns>
//public static bool ValidCardNumber(string CardNumber)
//{
// System.Text.RegularExpressions.Regex reg1
// = new System.Text.RegularExpressions.Regex(@"^\d{15}|(\d{17}(\d|X|*))$");
// return reg1.IsMatch(CardNumber);
//}
#region 得到一个不重复的文件名
/// <summary>
/// 得到一个不重复的文件名(年月日_时分秒_微秒_UserSeqID)
/// </summary>
/// <param name="strUserSeqID">当前操作用户的UserSeqID</param>
/// <returns>得到一个不重复的文件名字符串(年月日_时分秒_微秒_UserSeqID)</returns>
public static string GetAFileNameString(string strUserSeqID)
{
string strTemp, strYear, strMonth, strDay, strHour, strMinute, strSecond, strMillisecond;
DateTime dt = DateTime.Now;
strYear = dt.Year.ToString();
strMonth = (dt.Month > 9) ? dt.Month.ToString() : "0" + dt.Month.ToString();
strDay = (dt.Day > 9) ? dt.Day.ToString() : "0" + dt.Day.ToString();
strHour = (dt.Hour > 9) ? dt.Hour.ToString() : "0" + dt.Hour.ToString();
strMinute = (dt.Minute > 9) ? dt.Minute.ToString() : "0" + dt.Minute.ToString();
strSecond = (dt.Second > 9) ? dt.Second.ToString() : "0" + dt.Second.ToString();
strMillisecond = dt.Millisecond.ToString();
strTemp = strYear + strMonth + strDay + "_" + strHour + strMinute + strSecond + "_" + strMillisecond + "_" + strUserSeqID.Trim();
return strTemp;
}
#endregion
#region 生成随机数(作为旅行社订单号)
/// <summary>
/// 生成随机数(旅游线路订单号)
/// </summary>
/// <returns></returns>
public static long GetRanDomNumeric()
{
Random RD = new Random();
long tempRD = (long)RD.Next(1000);
string newfilename = DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString()
+ DateTime.Now.Day.ToString() + DateTime.Now.Hour.ToString()
+ DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString()
+ DateTime.Now.Millisecond.ToString();
return long.Parse(newfilename) + tempRD;
//return DateTime.Now.Ticks;
}
#endregion
/// <summary>
/// 随机数字组合成新的字符串
/// </summary>
/// <param name="FileName"></param>
/// <returns></returns>
public static string GetNewFileName(string FileName)
{
//跟据文件名产生一个由时间+随机数组成的一个新的文件名
string newfilename = DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString()
+ DateTime.Now.Day.ToString() + DateTime.Now.Hour.ToString()
+ DateTime.Now.Second.ToString() + DateTime.Now.Minute.ToString()
+ DateTime.Now.Millisecond.ToString()
+ FileName.Substring(FileName.LastIndexOf("."), FileName.Length - FileName.LastIndexOf("."));
return newfilename;
}