62,243
社区成员




public static string CutString(this string value, int length)
{
if (string.IsNullOrEmpty(value)) return "";
int dataLength = length * 2; //要截取的字节长度
byte[] bLength = Encoding.GetEncoding("gb2312").GetBytes(value); //原字符串的字节长度
if (bLength.Length <= dataLength)
return value;
string strEndRes = "";
while (true)
{
strEndRes += value.Substring(strEndRes.Length, length);
int size = dataLength - Encoding.GetEncoding("gb2312").GetBytes(strEndRes).Length;
if (size <= 1)
{
if (size == 1 && Encoding.GetEncoding("gb2312").GetBytes(value.Substring(strEndRes.Length, 1)).Length == 1)
{
strEndRes += value.Substring(strEndRes.Length, 1);
}
return strEndRes;
}
length = size / 2;
}
}
/// <summary>
/// 截取指定长度中英文字符串(宽度一样)
/// </summary>
/// <param name="str">要截取的字符串</param>
/// <param name="length">截取长度,中文字符长度</param>
/// <returns>截取后的字符串</returns>
public static string CutStr(object str, int length)
{
if (str == null) return string.Empty;
Encoding encoding = Encoding.GetEncoding("gb2312");
int len = length * 2;
int j = 0, k = 0;
string cutStr = str.ToString();
for (int i = 0; i < cutStr.Length; i++)
{
byte[] bytes = encoding.GetBytes(cutStr.Substring(i, 1));
if (bytes.Length == 2)//不是英文
j += 2;
else
j++;
if (j <= len)
k += 1;
if (j >= len)
return cutStr.Substring(0, k) + "...";
}
return cutStr;
}
/// <summary>
/// 下载指定路径文件
/// </summary>
/// <param name="path">文件绝对路径</param>
public static void DownLoadFile(string path)
{
System.IO.FileInfo fi = new System.IO.FileInfo(path);
if (fi.Exists)
{
//判断文件是否正在使用
try
{
using (System.IO.FileStream fs = System.IO.File.Open(path, System.IO.FileMode.Append, System.IO.FileAccess.Write, System.IO.FileShare.None))
{
}
}
catch (Exception ex)
{
throw;
}
System.Web.HttpContext.Current.Response.Clear();
System.Web.HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(path.Substring(path.LastIndexOf("\\") + 1), System.Text.Encoding.UTF8));
System.Web.HttpContext.Current.Response.AddHeader("Content-Length", fi.Length.ToString());
System.Web.HttpContext.Current.Response.ContentType = "application/octet-stream;charset=gb2321";
System.Web.HttpContext.Current.Response.WriteFile(fi.FullName);
System.Web.HttpContext.Current.Response.Flush();
System.Web.HttpContext.Current.Response.Close();
}
else
{
System.Web.HttpContext.Current.Response.Write("<script>alert('源文件不存在!');</script>");
}
}
/// <summary>
/// 获取枚举的描述信息
/// </summary>
/// <param name="en">枚举</param>
/// <returns></returns>
public static string GetEnumDescription(this Enum en)
{
Type type = en.GetType();
System.Reflection.MemberInfo[] memInfo = type.GetMember(en.ToString());
if (memInfo != null && memInfo.Length > 0)
{
object[] attrs = memInfo[0].GetCustomAttributes(typeof(System.ComponentModel.DescriptionAttribute), false);
if (attrs != null && attrs.Length > 0)
return ((System.ComponentModel.DescriptionAttribute)attrs[0]).Description;
}
return en.ToString();
}
/// <summary>
/// 通用应用程序缓存辅助类
/// </summary>
public static class CacheHelper
{
public delegate T GetDataMethod<T>();//获取数据的方法
/// <summary>
/// 通用应用程序缓存方法,缓存数据10分钟
/// </summary>
/// <typeparam name="T">缓存数据的类型,一般是集合,如IList<UsersData></typeparam>
/// <param name="key">键</param>
/// <param name="getDataMethod">获取数据的方法</param>
/// <returns>数据列表</returns>
public static T GetCache<T>(string key, GetDataMethod<T> getDataMethod)
{
//T dataList = getDataMethod();
//return dataList;
if (HttpRuntime.Cache[key] == null)
{
T dataList = getDataMethod();
HttpRuntime.Cache.Add(key, dataList, null, DateTime.Now.AddMinutes(10),
TimeSpan.Zero, System.Web.Caching.CacheItemPriority.High, null);
return dataList;
}
return (T)HttpRuntime.Cache[key];
}
/// <summary>
/// 移除应用程序缓存
/// </summary>
/// <param name="key">键</param>
public static void RemoveCacheByKey(string key)
{
HttpRuntime.Cache.Remove(key);
}
}
/// <summary>
/// 获取用户IP地址
/// </summary>
public static string IPAddress
{
get
{
//string ipAddress = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
//HTTP_X_FORWARDED_FOR获取的用户真实ip可能存在欺骗,所以忽略通过代理的访问的用户真实ip地址,记录代理ip
string ipAddress = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
if (string.IsNullOrEmpty(ipAddress))
ipAddress = HttpContext.Current.Request.UserHostAddress;
if (ipAddress.Length > 15) //是ipv6格式ip,转换为ipv4
{
//取得客户端主机 IPv4 位址(通过DNS反查)
string ipv4 = string.Empty;
foreach (System.Net.IPAddress ip in System.Net.Dns.GetHostAddresses(ipAddress))
{
if (ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
{
ipv4 = ip.ToString();
break;
}
}
if (ipv4.Length == 0)
{
foreach (System.Net.IPAddress ip2 in System.Net.Dns.GetHostEntry(ipAddress).AddressList)
{
if (ip2.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
{
ipv4 = ip2.ToString();
break;
}
}
}
return ipv4.Length > 0 ? ipv4 : string.Empty;
}
return ipAddress;
}
}
#region Cookie操作
/// <summary>
/// 设置指定Cookie名称的值
/// </summary>
/// <param name="cookieName">cookie名称</param>
/// <param name="cookieValue">值</param>
/// <param name="expires">过期时间,DateTime.MinValue表示默认过期时间</param>
public static void AddCookie(string cookieName, string cookieValue, DateTime expires)
{
HttpContext.Current.Response.Cookies[cookieName].Value = string.Empty;
HttpContext.Current.Response.Cookies[cookieName].Value = cookieValue;
if (expires != DateTime.MinValue)
HttpContext.Current.Response.Cookies[cookieName].Expires = expires;
}
/// <summary>
/// 读取指定cookie名称的值
/// </summary>
/// <param name="cookieName">cookie名称</param>
/// <returns>值</returns>
public static string GetCookie(string cookieName)
{
string cookieValue = string.Empty;
try
{
cookieValue = HttpContext.Current.Request.Cookies[cookieName].Value;
}
catch { }
return cookieValue;
}
/// <summary>
/// 删除指定名称cookie
/// </summary>
/// <param name="cookieName">cookie名称</param>
public static void RemoveCookie(string cookieName)
{
HttpContext.Current.Response.Cookies[cookieName].Expires = DateTime.MinValue;
}
#endregion