public class Common
{
/// <summary>
/// 清除HTML标记且返回相应的长度
/// </summary>
/// <param name="Htmlstring"></param>
/// <param name="strLen"></param>
/// <returns></returns>
public static string DropHTML(string Htmlstring, int strLen)
{
return CutString(DropHTML(Htmlstring), strLen);
}
/// <summary>
/// 截取字符长度
/// </summary>
/// <param name="inputString">字符</param>
/// <param name="len">长度</param>
/// <returns></returns>
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 = Encoding.UTF8.GetBytes(inputString);
if (mybyte.Length > len)
tempString += "…";
return tempString;
}
/// <summary>
/// 清楚html标签
/// </summary>
/// <param name="Htmlstring"></param>
/// <returns></returns>
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, @"<!--.*", "", 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", "");
Htmlstring.Replace(" ", "");
Htmlstring = WebUtility.HtmlEncode(Htmlstring).Trim();
return Htmlstring;
}
/// <summary>
/// 得到Mime类型
/// </summary>
/// <param name="fileName">文件名</param>
/// <returns></returns>
public static string GetMimeType(string fileName)
{
string mimeType = "application/unknown";
string ext = Path.GetExtension(fileName).ToLower();
RegistryKey regKey = Registry.ClassesRoot.OpenSubKey(ext);
if (regKey != null && regKey.GetValue("Content Type") != null)
{
mimeType = regKey.GetValue("Content Type").ToString();
}
return mimeType;
}
/// <summary>
/// 时间格式化
/// </summary>
/// <param name="lastTime"></param>
/// <returns></returns>
public static string ConverTime(DateTime lastTime)
{
DateTime nowTime = DateTime.Now; //获取当前时间
TimeSpan timeSn = nowTime - lastTime;
double timeLength = timeSn.TotalSeconds;
string str = "";
if (timeLength <= 60 * 3)
{
str = "刚刚";
}
else if (0 < timeLength && timeLength <= 60 * 15)
{
str = Convert.ToInt32(timeLength / 60) + "分钟前";
}
else if (60 * 15 < timeLength && timeLength <= 60 * 30)
{
str = "半小时前";
}
else if (60 * 30 < timeLength && timeLength <= 60 * 60)
{
str = "1小时前";
}
else if (60 * 60 < timeLength && timeLength <= 60 * 60 * 24)
{
str = Convert.ToInt32(timeLength / 3600) + "小时前";
}
else if (60 * 60 * 24 < timeLength && timeLength <= 60 * 60 * 24 * 30)
{
str = Convert.ToInt32(timeLength / 3600 / 24) + "天前";
}
else if (60 * 60 * 24 * 30 < timeLength && timeLength < 60 * 60 * 24 * 30 * 12)
{
str = Convert.ToInt32(timeLength / 3600 / 24 / 30) + "月前";
}
else if (60 * 60 * 24 * 30 * 12 < timeLength)
{
str = Convert.ToInt32(timeLength / 3600 / 24 / 30 / 12) + "年前";
}
return str;
}
#region 生成0-9随机数
/// <summary>
/// 生成0-9随机数
/// </summary>
/// <param name="codeNum">生成长度</param>
/// <returns></returns>
public static string RndNum(int codeNum)
{
StringBuilder sb = new StringBuilder(codeNum);
Random rand = new Random();
for (int i = 1; i < codeNum + 1; i++)
{
int t = rand.Next(9);
sb.AppendFormat("{0}", t);
}
return sb.ToString();
}
/// <summary>
/// 生成随机字母
/// </summary>
/// <param name="Length">生成长度</param>
/// <returns></returns>
public static string GenerateRandom(int Length)
{
char[] constant ={
'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'
};
System.Text.StringBuilder newRandom = new System.Text.StringBuilder(52);
Random rd = new Random();
for (int i = 0; i < Length; i++)
{
newRandom.Append(constant[rd.Next(52)]);
}
return newRandom.ToString();
}
/// <summary>
/// 生成账户名(昵称)
/// </summary>
/// <returns></returns>
public static string GetUserFullName(string prefix)
{
int[] aInt = new int[] { 6, 7, 8, 9, 10 };
Random rand = new Random();
int t = rand.Next(aInt.Length);
return (prefix + GenerateCheckCode(aInt[t])).ToLower();
}
/// <summary>
/// 生成随机字母字符串(数字字母混和)
/// </summary>
/// <param name="codeCount">待生成的位数</param>
/// <returns> 生成的字母字符串</returns>
public static string GenerateCheckCode(int codeCount)
{
int rep = 0;
string str = string.Empty;
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 int GetRandomNumber(int min, int max)
{
int rtn = 0;
Random r = new Random();
byte[] buffer = Guid.NewGuid().ToByteArray();
int iSeed = BitConverter.ToInt32(buffer, 0);
r = new Random(iSeed);
rtn = r.Next(min, max + 1);
return rtn;
}
#endregion
/// <summary>
/// 元转万元
/// </summary>
/// <param name="decIn"></param>
/// <returns></returns>
public static decimal YToWan(decimal? decIn)
{
decimal decResult = 0.00M;
if (!string.IsNullOrEmpty(decIn.ToString()))
{
decResult = Math.Round(decimal.Parse((decIn * 0.0001M).ToString()), 2);
}
return decResult;
}
/// <summary>
/// 万元转元
/// </summary>
/// <param name="decIn"></param>
/// <returns></returns>
public static decimal WToYuan(decimal? decIn)
{
decimal decResult = 0.00M;
if (!string.IsNullOrEmpty(decIn.ToString()))
{
decResult = Math.Round((decimal)decIn * 10000, 2);
}
return decResult;
}
/// <summary>
/// HTTP POST 请求方法
/// </summary>
/// <param name="uri">请求地址域名</param>
/// <param name="url">请求方法</param>
/// <param name="formData">请求参数</param>
/// <returns></returns>
public static string HttpPost(string uri, string url, Dictionary<string, string> formData)
{
try {
string charset = "UTF-8";
string mediaType = "application/x-www-form-urlencoded";
string tokenUri = url;
var client = new HttpClient();
client.BaseAddress = new Uri(uri);
HttpContent content = new FormUrlEncodedContent(formData);
content.Headers.ContentType = new MediaTypeHeaderValue(mediaType);
content.Headers.ContentType.CharSet = charset;
foreach (var a in formData)
{
content.Headers.Add(a.Key, a.Value);
}
//string strParma = Newtonsoft.Json.JsonConvert.SerializeObject(formData);
//content.Headers.Add("aa", strParma.ToString());
var res = client.PostAsync(tokenUri, content);
res.Wait();
HttpResponseMessage resp = res.Result;
var res2 = resp.Content.ReadAsStringAsync();
res2.Wait();
string token = res2.Result;
return token;
}
catch (Exception ex) {
return ex.Message;
}
}
/// <summary>
/// HTTP GET 请求方法
/// </summary>
/// <param name="url">请求地址</param>
/// <param name="formData">请求参数</param>
/// <returns></returns>
public static string HttpGet(string url, Dictionary<string, string> formData)
{
HttpClient httpClient = new HttpClient();
HttpContent content = new FormUrlEncodedContent(formData);
if (formData != null)
{
content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
content.Headers.ContentType.CharSet = "UTF-8";
foreach (var a in formData)
{
content.Headers.Add(a.Key, a.Value);
}
}
var request = new HttpRequestMessage()
{
RequestUri = new Uri(url),
Method = HttpMethod.Get,
};
foreach (var a in formData)
{
request.Headers.Add(a.Key, a.Value);
}
var res = httpClient.SendAsync(request);
res.Wait();
var resp = res.Result;
Task<string> temp = resp.Content.ReadAsStringAsync();
temp.Wait();
return temp.Result;
}
/// <summary>
/// 此代码示例通过创建哈希字符串适用于任何 MD5 哈希函数 (在任何平台) 上创建 32 个字符的十六进制格式哈希字符串
/// 官网案例改编
/// </summary>
/// <param name="source"></param>
/// <returns></returns>
public static string Get32MD5One(string source)
{
using (System.Security.Cryptography.MD5 md5Hash = System.Security.Cryptography.MD5.Create())
{
byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(source));
StringBuilder sBuilder = new StringBuilder();
for (int i = 0; i < data.Length; i++)
{
sBuilder.Append(data[i].ToString("x2"));
}
string hash = sBuilder.ToString();
return hash.ToUpper();
}
}
public const string REG_TEL = @"^1\d{10}$"; //手机
public const string REG_FIXEDTEL = @"^((0\d{2,3})(-|\s+)?)(\d{7,8})((-|\s+)?(\d{3,}))?$"; //固话
public const string REG_EMAIL = @"^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$"; //邮箱
public const string REG_FAX = @"^(\d{3,4}-)?\d{7,8}$"; //传真
public const string REG_WEBSITE = @"^((http|ftp|https)://)?(([a-zA-Z0-9\._-]+\.[a-zA-Z]{2,6})|([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}))(:[0-9]{1,4})*(/[a-zA-Z0-9\&%_\./-~-]*)?$"; //网址
public const string REG_CARJIA = @"^[A-Za-z0-9]{17}$";//车架号
public const string REG_PASSWORK = @"^[A-Za-z0-9]{8,16}$";//密码
public const string REG_NAME = @"^[a-zA-Z0-9\u4E00-\u9FFF]{1,20}$";//用户名
public const string REG_VIDEOLINK = @"(?i)^(((https?|ftp):\/\/|\w+(\.\w+)+)(:\w+)?).+(\.mp4|\.flv)$";//视频链接
public const string REG_CODEFLAG = @"^0\d{4}$";//二维码标识