博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
web开发过程中经常用到的一些公共方法及操作
阅读量:6573 次
发布时间:2019-06-24

本文共 74106 字,大约阅读时间需要 247 分钟。

进化成为程序猿也有段岁月了,所谓的经验,广度还是依旧,只不过是对于某种功能有了多种实现方式的想法。每天依旧不厌其烦的敲打着代码,每一行代码的回车似乎都有一种似曾相识的感觉。于是乎:粘贴复制,再粘贴再复制一个网站成型,一个系统上线。

网络给猿类提供了大量的资源及可复制的代码,难道经验就是每次相同问题查找浪费掉的时间所积累出来的吗?当然不是了,为了快速方便的查找一些经常用到的方法,将剩余的时间用来研究一些新的技术提高自己开发经验的含金量,博主把平时自己总结的一些东西及在网上借鉴到的一些方法贴出来与大家共享

首先列举一个最近遇到的一个框架问题:

页面框架设计如下:

其中一个子页面在后台添加成功之后让tab选项卡切换的实现

//先在父页面定义一个全局变量 var tab = null; $(function () {      tab = $("#tabs").tabs(); });

 然后在子页面通过window.parent.tab.tabs({ selected:1 });

 window.parent.document.getElementById('Iframe2').src = 'RiskTypeEdit.aspx?ID=1' 这种方式切换.

顺便说下 parent和opener的区别

opener用于在window.open的页面引用执行该window.open方法的的页面的对象

parent用于在iframe,frame中生成的子页面中访问父页面的对象

parent是相对于框架来说父窗口对象 opener是针对于用window.open打开的窗口来说的父窗口,前提是window.open打开的才有。

1、JSON转换操作

包含List转换成Json的默认格式;List转换成Json处定义格式;对象转换为Json;对象集合转换Json;普通集合转换Json;DataSet转换为Json;Datatable转换为Json;DataReader转换为Json

#region 私有方法        ///         /// 过滤特殊字符        ///         private static string String2Json(String s)        {            StringBuilder sb = new StringBuilder();            for (int i = 0; i < s.Length; i++)            {                char c = s.ToCharArray()[i];                switch (c)                {                    case '\"':                        sb.Append("\\\""); break;                    case '\\':                        sb.Append("\\\\"); break;                    case '/':                        sb.Append("\\/"); break;                    case '\b':                        sb.Append("\\b"); break;                    case '\f':                        sb.Append("\\f"); break;                    case '\n':                        sb.Append("\\n"); break;                    case '\r':                        sb.Append("\\r"); break;                    case '\t':                        sb.Append("\\t"); break;                    default:                        sb.Append(c); break;                }            }            return sb.ToString();        }                ///         /// 格式化字符型、日期型、布尔型        ///         private static string StringFormat(string str, Type type)        {            if (type == typeof(string))            {                str = String2Json(str);                str = "\"" + str + "\"";            }            else if (type == typeof(DateTime))            {                str = "\"" + str + "\"";            }            else if (type == typeof(bool))            {                str = str.ToLower();            }            else if (type != typeof(string) && string.IsNullOrEmpty(str))            {                str = "\"" + str + "\"";            }            return str;        }        #endregion        #region List转换成Json        ///         /// List转换成Json        ///         public static string ListToJson
(IList
list) { object obj = list[0]; return ListToJson
(list, obj.GetType().Name); } ///
/// List转换成Json /// public static string ListToJson
(IList
list, string jsonName) { StringBuilder Json = new StringBuilder(); if (string.IsNullOrEmpty(jsonName)) jsonName = list[0].GetType().Name; Json.Append("{\"" + jsonName + "\":["); if (list.Count > 0) { for (int i = 0; i < list.Count; i++) { T obj = Activator.CreateInstance
(); PropertyInfo[] pi = obj.GetType().GetProperties(); Json.Append("{ "); for (int j = 0; j < pi.Length; j++) { Type type = pi[j].GetValue(list[i], null).GetType(); Json.Append("\"" + pi[j].Name.ToString() + "\":" + StringFormat(pi[j].GetValue(list[i], null).ToString(), type)); if (j < pi.Length - 1) { Json.Append(","); } } Json.Append("}"); if (i < list.Count - 1) { Json.Append(","); } } } Json.Append("]}"); return Json.ToString(); } #endregion #region 对象转换为Json ///
/// 对象转换为Json /// ///
对象 ///
Json字符串
public static string ToJson(object jsonObject) { string jsonString = "{ "; PropertyInfo[] propertyInfo = jsonObject.GetType().GetProperties(); for (int i = 0; i < propertyInfo.Length; i++) { object objectValue = propertyInfo[i].GetGetMethod().Invoke(jsonObject, null); string value = string.Empty; if (objectValue is DateTime || objectValue is Guid || objectValue is TimeSpan) { value = "'" + objectValue.ToString() + "'"; } else if (objectValue is string) { value = "'" + ToJson(objectValue.ToString()) + "'"; } else if (objectValue is IEnumerable) { value = ToJson((IEnumerable)objectValue); } else { value = ToJson(objectValue.ToString()); } jsonString += "\"" + ToJson(propertyInfo[i].Name) + "\":" + value + ","; } jsonString.Remove(jsonString.Length - 1, jsonString.Length); return jsonString + "}"; } #endregion #region 对象集合转换Json ///
/// 对象集合转换Json /// ///
集合对象 ///
Json字符串
public static string ToJson(IEnumerable array) { string jsonString = "["; foreach (object item in array) { jsonString += ToJson(item) + ","; } jsonString.Remove(jsonString.Length - 1, jsonString.Length); return jsonString + "]"; } #endregion #region 普通集合转换Json ///
/// 普通集合转换Json /// ///
集合对象 ///
Json字符串
public static string ToArrayString(IEnumerable array) { string jsonString = "["; foreach (object item in array) { jsonString = ToJson(item.ToString()) + ","; } jsonString.Remove(jsonString.Length - 1, jsonString.Length); return jsonString + "]"; } #endregion #region DataSet转换为Json ///
/// DataSet转换为Json /// ///
DataSet对象 ///
Json字符串
public static string ToJson(DataSet dataSet) { string jsonString = "{ "; foreach (DataTable table in dataSet.Tables) { jsonString += "\"" + table.TableName + "\":" + ToJson(table) + ","; } jsonString = jsonString.TrimEnd(','); return jsonString + "}"; } #endregion #region Datatable转换为Json ///
/// Datatable转换为Json /// ///
Datatable对象 ///
Json字符串
public static string ToJson(DataTable dt) { StringBuilder jsonString = new StringBuilder(); jsonString.Append("["); DataRowCollection drc = dt.Rows; for (int i = 0; i < drc.Count; i++) { jsonString.Append("{ "); for (int j = 0; j < dt.Columns.Count; j++) { string strKey = dt.Columns[j].ColumnName; string strValue = drc[i][j].ToString(); Type type = dt.Columns[j].DataType; jsonString.Append("\"" + strKey + "\":"); strValue = StringFormat(strValue, type); if (j < dt.Columns.Count - 1) { jsonString.Append(strValue + ","); } else { jsonString.Append(strValue); } } jsonString.Append("},"); } jsonString.Remove(jsonString.Length - 1, 1); jsonString.Append("]"); return jsonString.ToString(); } ///
/// DataTable转换为Json /// public static string ToJson(DataTable dt, string jsonName) { StringBuilder Json = new StringBuilder(); if (string.IsNullOrEmpty(jsonName)) jsonName = dt.TableName; Json.Append("{\"" + jsonName + "\":["); if (dt.Rows.Count > 0) { for (int i = 0; i < dt.Rows.Count; i++) { Json.Append("{ "); for (int j = 0; j < dt.Columns.Count; j++) { Type type = dt.Rows[i][j].GetType(); Json.Append("\"" + dt.Columns[j].ColumnName.ToString() + "\":" + StringFormat(dt.Rows[i][j].ToString(), type)); if (j < dt.Columns.Count - 1) { Json.Append(","); } } Json.Append("}"); if (i < dt.Rows.Count - 1) { Json.Append(","); } } } Json.Append("]}"); return Json.ToString(); } #endregion #region DataReader转换为Json ///
/// DataReader转换为Json /// ///
DataReader对象 ///
Json字符串
public static string ToJson(DbDataReader dataReader) { StringBuilder jsonString = new StringBuilder(); jsonString.Append("["); while (dataReader.Read()) { jsonString.Append("{ "); for (int i = 0; i < dataReader.FieldCount; i++) { Type type = dataReader.GetFieldType(i); string strKey = dataReader.GetName(i); string strValue = dataReader[i].ToString(); jsonString.Append("\"" + strKey + "\":"); strValue = StringFormat(strValue, type); if (i < dataReader.FieldCount - 1) { jsonString.Append(strValue + ","); } else { jsonString.Append(strValue); } } jsonString.Append("},"); } dataReader.Close(); jsonString.Remove(jsonString.Length - 1, 1); jsonString.Append("]"); return jsonString.ToString(); } #endregion
View Code

2、XML操作类

///     /// Xml的操作公共类    ///         public class XmlHelper    {        #region 字段定义        ///         /// XML文件的物理路径        ///         private string _filePath = string.Empty;        ///         /// Xml文档        ///         private XmlDocument _xml;        ///         /// XML的根节点        ///         private XmlElement _element;        #endregion        #region 构造方法        ///         /// 实例化XmlHelper对象        ///         /// Xml文件的相对路径        public XmlHelper(string xmlFilePath)        {            //获取XML文件的绝对路径            _filePath = SysHelper.GetPath(xmlFilePath);        }        #endregion        #region 创建XML的根节点        ///         /// 创建XML的根节点        ///         private void CreateXMLElement()        {            //创建一个XML对象            _xml = new XmlDocument();            if (DirFile.IsExistFile(_filePath))            {                //加载XML文件                _xml.Load(this._filePath);            }            //为XML的根节点赋值            _element = _xml.DocumentElement;        }        #endregion        #region 获取指定XPath表达式的节点对象        ///         /// 获取指定XPath表达式的节点对象        ///                 /// XPath表达式,        /// 范例1: @"Skill/First/SkillItem", 等效于 @"//Skill/First/SkillItem"        /// 范例2: @"Table[USERNAME='a']" , []表示筛选,USERNAME是Table下的一个子节点.        /// 范例3: @"ApplyPost/Item[@itemName='岗位编号']",@itemName是Item节点的属性.        ///         public XmlNode GetNode(string xPath)        {            //创建XML的根节点            CreateXMLElement();            //返回XPath节点            return _element.SelectSingleNode(xPath);        }        #endregion        #region 获取指定XPath表达式节点的值        ///         /// 获取指定XPath表达式节点的值        ///         /// XPath表达式,        /// 范例1: @"Skill/First/SkillItem", 等效于 @"//Skill/First/SkillItem"        /// 范例2: @"Table[USERNAME='a']" , []表示筛选,USERNAME是Table下的一个子节点.        /// 范例3: @"ApplyPost/Item[@itemName='岗位编号']",@itemName是Item节点的属性.        ///         public string GetValue(string xPath)        {            //创建XML的根节点            CreateXMLElement();            //返回XPath节点的值            return _element.SelectSingleNode(xPath).InnerText;        }        #endregion        #region 获取指定XPath表达式节点的属性值        ///         /// 获取指定XPath表达式节点的属性值        ///         /// XPath表达式,        /// 范例1: @"Skill/First/SkillItem", 等效于 @"//Skill/First/SkillItem"        /// 范例2: @"Table[USERNAME='a']" , []表示筛选,USERNAME是Table下的一个子节点.        /// 范例3: @"ApplyPost/Item[@itemName='岗位编号']",@itemName是Item节点的属性.        ///         /// 属性名        public string GetAttributeValue(string xPath, string attributeName)        {            //创建XML的根节点            CreateXMLElement();            //返回XPath节点的属性值            return _element.SelectSingleNode(xPath).Attributes[attributeName].Value;        }        #endregion        #region 新增节点        ///         /// 1. 功能:新增节点。        /// 2. 使用条件:将任意节点插入到当前Xml文件中。        ///                 /// 要插入的Xml节点        public void AppendNode(XmlNode xmlNode)        {            //创建XML的根节点            CreateXMLElement();            //导入节点            XmlNode node = _xml.ImportNode(xmlNode, true);            //将节点插入到根节点下            _element.AppendChild(node);        }        ///         /// 1. 功能:新增节点。        /// 2. 使用条件:将DataSet中的第一条记录插入Xml文件中。        ///                 /// DataSet的实例,该DataSet中应该只有一条记录        public void AppendNode(DataSet ds)        {            //创建XmlDataDocument对象            XmlDataDocument xmlDataDocument = new XmlDataDocument(ds);            //导入节点            XmlNode node = xmlDataDocument.DocumentElement.FirstChild;            //将节点插入到根节点下            AppendNode(node);        }        #endregion        #region 删除节点        ///         /// 删除指定XPath表达式的节点        ///                 /// XPath表达式,        /// 范例1: @"Skill/First/SkillItem", 等效于 @"//Skill/First/SkillItem"        /// 范例2: @"Table[USERNAME='a']" , []表示筛选,USERNAME是Table下的一个子节点.        /// 范例3: @"ApplyPost/Item[@itemName='岗位编号']",@itemName是Item节点的属性.        ///         public void RemoveNode(string xPath)        {            //创建XML的根节点            CreateXMLElement();            //获取要删除的节点            XmlNode node = _xml.SelectSingleNode(xPath);            //删除节点            _element.RemoveChild(node);        }        #endregion //删除节点        #region 保存XML文件        ///         /// 保存XML文件        ///                 public void Save()        {            //创建XML的根节点            CreateXMLElement();            //保存XML文件            _xml.Save(this._filePath);        }        #endregion //保存XML文件        #region 静态方法        #region 创建根节点对象        ///         /// 创建根节点对象        ///         /// Xml文件的相对路径                private static XmlElement CreateRootElement(string xmlFilePath)        {            //定义变量,表示XML文件的绝对路径            string filePath = "";            //获取XML文件的绝对路径            filePath = SysHelper.GetPath(xmlFilePath);            //创建XmlDocument对象            XmlDocument xmlDocument = new XmlDocument();            //加载XML文件            xmlDocument.Load(filePath);            //返回根节点            return xmlDocument.DocumentElement;        }        #endregion        #region 获取指定XPath表达式节点的值        ///         /// 获取指定XPath表达式节点的值        ///         /// Xml文件的相对路径        /// XPath表达式,        /// 范例1: @"Skill/First/SkillItem", 等效于 @"//Skill/First/SkillItem"        /// 范例2: @"Table[USERNAME='a']" , []表示筛选,USERNAME是Table下的一个子节点.        /// 范例3: @"ApplyPost/Item[@itemName='岗位编号']",@itemName是Item节点的属性.        ///         public static string GetValue(string xmlFilePath, string xPath)        {            //创建根对象            XmlElement rootElement = CreateRootElement(xmlFilePath);            //返回XPath节点的值            return rootElement.SelectSingleNode(xPath).InnerText;        }        #endregion        #region 获取指定XPath表达式节点的属性值        ///         /// 获取指定XPath表达式节点的属性值        ///         /// Xml文件的相对路径        /// XPath表达式,        /// 范例1: @"Skill/First/SkillItem", 等效于 @"//Skill/First/SkillItem"        /// 范例2: @"Table[USERNAME='a']" , []表示筛选,USERNAME是Table下的一个子节点.        /// 范例3: @"ApplyPost/Item[@itemName='岗位编号']",@itemName是Item节点的属性.        ///         /// 属性名        public static string GetAttributeValue(string xmlFilePath, string xPath, string attributeName)        {            //创建根对象            XmlElement rootElement = CreateRootElement(xmlFilePath);            //返回XPath节点的属性值            return rootElement.SelectSingleNode(xPath).Attributes[attributeName].Value;        }        #endregion        #endregion        public static void SetValue(string xmlFilePath, string xPath, string newtext)        {            //string path = SysHelper.GetPath(xmlFilePath);            //var queryXML = from xmlLog in xelem.Descendants("msg_log")            //               //所有名字为Bin的记录            //               where xmlLog.Element("user").Value == "Bin"            //               select xmlLog;            //foreach (XElement el in queryXML)            //{            //    el.Element("user").Value = "LiuBin";//开始修改            //}            //xelem.Save(path);        }    }
View Code

3、文件下载

public class FileDown    {        public FileDown()        { }        ///         /// 参数为虚拟路径        ///         public static string FileNameExtension(string FileName)        {            return Path.GetExtension(MapPathFile(FileName));        }        ///         /// 获取物理地址        ///         public static string MapPathFile(string FileName)        {            return HttpContext.Current.Server.MapPath(FileName);        }        ///         /// 普通下载        ///         /// 文件虚拟路径        public static void DownLoadold(string FileName)        {            string destFileName = MapPathFile(FileName);            if (File.Exists(destFileName))            {                FileInfo fi = new FileInfo(destFileName);                HttpContext.Current.Response.Clear();                HttpContext.Current.Response.ClearHeaders();                HttpContext.Current.Response.Buffer = false;                HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(Path.GetFileName(destFileName), System.Text.Encoding.UTF8));                HttpContext.Current.Response.AppendHeader("Content-Length", fi.Length.ToString());                HttpContext.Current.Response.ContentType = "application/octet-stream";                HttpContext.Current.Response.WriteFile(destFileName);                HttpContext.Current.Response.Flush();                HttpContext.Current.Response.End();            }        }        ///         /// 分块下载        ///         /// 文件虚拟路径        public static void DownLoad(string FileName)        {            string filePath = MapPathFile(FileName);            long chunkSize = 204800;             //指定块大小             byte[] buffer = new byte[chunkSize]; //建立一个200K的缓冲区             long dataToRead = 0;                 //已读的字节数               FileStream stream = null;            try            {                //打开文件                   stream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);                dataToRead = stream.Length;                //添加Http头                   HttpContext.Current.Response.ContentType = "application/octet-stream";                HttpContext.Current.Response.AddHeader("Content-Disposition", "attachement;filename=" + HttpUtility.UrlEncode(Path.GetFileName(filePath)));                HttpContext.Current.Response.AddHeader("Content-Length", dataToRead.ToString());                while (dataToRead > 0)                {                    if (HttpContext.Current.Response.IsClientConnected)                    {                        int length = stream.Read(buffer, 0, Convert.ToInt32(chunkSize));                        HttpContext.Current.Response.OutputStream.Write(buffer, 0, length);                        HttpContext.Current.Response.Flush();                        HttpContext.Current.Response.Clear();                        dataToRead -= length;                    }                    else                    {                        dataToRead = -1; //防止client失去连接                     }                }            }            catch (Exception ex)            {                HttpContext.Current.Response.Write("Error:" + ex.Message);            }            finally            {                if (stream != null) stream.Close();                HttpContext.Current.Response.Close();            }        }        ///         ///  输出硬盘文件,提供下载 支持大文件、续传、速度限制、资源占用小        ///         /// Page.Request对象        /// Page.Response对象        /// 下载文件名        /// 带文件名下载路径        /// 每秒允许下载的字节数        /// 
返回是否成功
//--------------------------------------------------------------------- //调用: // string FullPath=Server.MapPath("count.txt"); // ResponseFile(this.Request,this.Response,"count.txt",FullPath,100); //--------------------------------------------------------------------- public static bool ResponseFile(HttpRequest _Request, HttpResponse _Response, string _fileName, string _fullPath, long _speed) { try { FileStream myFile = new FileStream(_fullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); BinaryReader br = new BinaryReader(myFile); try { _Response.AddHeader("Accept-Ranges", "bytes"); _Response.Buffer = false; long fileLength = myFile.Length; long startBytes = 0; int pack = 10240; //10K bytes int sleep = (int)Math.Floor((double)(1000 * pack / _speed)) + 1; if (_Request.Headers["Range"] != null) { _Response.StatusCode = 206; string[] range = _Request.Headers["Range"].Split(new char[] { '=', '-' }); startBytes = Convert.ToInt64(range[1]); } _Response.AddHeader("Content-Length", (fileLength - startBytes).ToString()); if (startBytes != 0) { _Response.AddHeader("Content-Range", string.Format(" bytes {0}-{1}/{2}", startBytes, fileLength - 1, fileLength)); } _Response.AddHeader("Connection", "Keep-Alive"); _Response.ContentType = "application/octet-stream"; _Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(_fileName, System.Text.Encoding.UTF8)); br.BaseStream.Seek(startBytes, SeekOrigin.Begin); int maxCount = (int)Math.Floor((double)((fileLength - startBytes) / pack)) + 1; for (int i = 0; i < maxCount; i++) { if (_Response.IsClientConnected) { _Response.BinaryWrite(br.ReadBytes(pack)); Thread.Sleep(sleep); } else { i = maxCount; } } } catch { return false; } finally { br.Close(); myFile.Close(); } } catch { return false; } return true; } }
View Code

4、ResponseFile输出下载

ResponseFile 输出硬盘文件,提供下载 支持大文件、续传、速度限制、资源占用小

public class DownLoadHelper    {        #region ResponseFile 输出硬盘文件,提供下载 支持大文件、续传、速度限制、资源占用小        ///         ///  输出硬盘文件,提供下载 支持大文件、续传、速度限制、资源占用小        ///         /// Page.Request对象        /// Page.Response对象        /// 下载文件名        /// 带文件名下载路径        /// 每秒允许下载的字节数        /// 
返回是否成功
public static bool ResponseFile(HttpRequest _Request, HttpResponse _Response, string _fileName, string _fullPath, long _speed) { try { FileStream myFile = new FileStream(_fullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); BinaryReader br = new BinaryReader(myFile); try { _Response.AddHeader("Accept-Ranges", "bytes"); _Response.Buffer = false; long fileLength = myFile.Length; long startBytes = 0; int pack = 10240; //10K bytes //int sleep = 200; //每秒5次 即5*10K bytes每秒 int sleep = (int)Math.Floor((double)(1000 * pack / _speed)) + 1; if (_Request.Headers["Range"] != null) { _Response.StatusCode = 206; string[] range = _Request.Headers["Range"].Split(new char[] { '=', '-' }); startBytes = Convert.ToInt64(range[1]); } _Response.AddHeader("Content-Length", (fileLength - startBytes).ToString()); if (startBytes != 0) { _Response.AddHeader("Content-Range", string.Format(" bytes {0}-{1}/{2}", startBytes, fileLength - 1, fileLength)); } _Response.AddHeader("Connection", "Keep-Alive"); _Response.ContentType = "application/octet-stream"; _Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(_fileName, System.Text.Encoding.UTF8)); br.BaseStream.Seek(startBytes, SeekOrigin.Begin); int maxCount = (int)Math.Floor((double)((fileLength - startBytes) / pack)) + 1; for (int i = 0; i < maxCount; i++) { if (_Response.IsClientConnected) { _Response.BinaryWrite(br.ReadBytes(pack)); Thread.Sleep(sleep); } else { i = maxCount; } } } catch { return false; } finally { br.Close(); myFile.Close(); } } catch { return false; } return true; } #endregion }
View Code

5、字符串操作

///     /// 字符串操作类    /// 1、GetStrArray(string str, char speater, bool toLower)  把字符串按照分隔符转换成 List    /// 2、GetStrArray(string str) 把字符串转 按照, 分割 换为数据    /// 3、GetArrayStr(List list, string speater) 把 List 按照分隔符组装成 string    /// 4、GetArrayStr(List list)  得到数组列表以逗号分隔的字符串    /// 5、GetArrayValueStr(Dictionary
list)得到数组列表以逗号分隔的字符串 /// 6、DelLastComma(string str)删除最后结尾的一个逗号 /// 7、DelLastChar(string str, string strchar)删除最后结尾的指定字符后的字符 /// 8、ToSBC(string input)转全角的函数(SBC case) /// 9、ToDBC(string input)转半角的函数(SBC case) /// 10、GetSubStringList(string o_str, char sepeater)把字符串按照指定分隔符装成 List 去除重复 /// 11、GetCleanStyle(string StrList, string SplitString)将字符串样式转换为纯字符串 /// 12、GetNewStyle(string StrList, string NewStyle, string SplitString, out string Error)将字符串转换为新样式 /// 13、SplitMulti(string str, string splitstr)分割字符串 /// 14、SqlSafeString(string String, bool IsDel) ///
public class StringHelper { /// /// 把字符串按照分隔符转换成 List /// /// 源字符串 /// 分隔符 /// 是否转换为小写 ///
public static List
GetStrArray(string str, char speater, bool toLower) { List
list = new List
(); string[] ss = str.Split(speater); foreach (string s in ss) { if (!string.IsNullOrEmpty(s) && s != speater.ToString()) { string strVal = s; if (toLower) { strVal = s.ToLower(); } list.Add(strVal); } } return list; } ///
/// 把字符串转 按照, 分割 换为数据 /// ///
///
public static string[] GetStrArray(string str) { return str.Split(new Char[] { ',' }); } ///
/// 把 List
按照分隔符组装成 string ///
///
///
///
public static string GetArrayStr(List
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(); } ///
/// 得到数组列表以逗号分隔的字符串 /// ///
///
public static string GetArrayStr(List
list) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < list.Count; i++) { if (i == list.Count - 1) { sb.Append(list[i].ToString()); } else { sb.Append(list[i]); sb.Append(","); } } return sb.ToString(); } ///
/// 得到数组列表以逗号分隔的字符串 /// ///
///
public static string GetArrayValueStr(Dictionary
list) { StringBuilder sb = new StringBuilder(); foreach (KeyValuePair
kvp in list) { sb.Append(kvp.Value + ","); } if (list.Count > 0) { return DelLastComma(sb.ToString()); } else { return ""; } } #region 删除最后一个字符之后的字符 ///
/// 删除最后结尾的一个逗号 /// public static string DelLastComma(string str) { return str.Substring(0, str.LastIndexOf(",")); } ///
/// 删除最后结尾的指定字符后的字符 /// public static string DelLastChar(string str, string strchar) { return str.Substring(0, str.LastIndexOf(strchar)); } #endregion ///
/// 转全角的函数(SBC case) /// ///
///
public static string ToSBC(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); } ///
/// 转半角的函数(SBC case) /// ///
输入 ///
public static string ToDBC(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); } ///
/// 把字符串按照指定分隔符装成 List 去除重复 /// ///
///
///
public static List
GetSubStringList(string o_str, char sepeater) { List
list = new List
(); string[] ss = o_str.Split(sepeater); foreach (string s in ss) { if (!string.IsNullOrEmpty(s) && s != sepeater.ToString()) { list.Add(s); } } return list; } #region 将字符串样式转换为纯字符串 ///
/// 将字符串样式转换为纯字符串 /// ///
///
///
public static string GetCleanStyle(string StrList, string SplitString) { string RetrunValue = ""; //如果为空,返回空值 if (StrList == null) { RetrunValue = ""; } else { //返回去掉分隔符 string NewString = ""; NewString = StrList.Replace(SplitString, ""); RetrunValue = NewString; } return RetrunValue; } #endregion #region 将字符串转换为新样式 ///
/// 将字符串转换为新样式 /// ///
///
///
///
///
public static string GetNewStyle(string StrList, string NewStyle, string SplitString, out string Error) { string ReturnValue = ""; //如果输入空值,返回空,并给出错误提示 if (StrList == null) { ReturnValue = ""; Error = "请输入需要划分格式的字符串"; } else { //检查传入的字符串长度和样式是否匹配,如果不匹配,则说明使用错误。给出错误信息并返回空值 int strListLength = StrList.Length; int NewStyleLength = GetCleanStyle(NewStyle, SplitString).Length; if (strListLength != NewStyleLength) { ReturnValue = ""; Error = "样式格式的长度与输入的字符长度不符,请重新输入"; } else { //检查新样式中分隔符的位置 string Lengstr = ""; for (int i = 0; i < NewStyle.Length; i++) { if (NewStyle.Substring(i, 1) == SplitString) { Lengstr = Lengstr + "," + i; } } if (Lengstr != "") { Lengstr = Lengstr.Substring(1); } //将分隔符放在新样式中的位置 string[] str = Lengstr.Split(','); foreach (string bb in str) { StrList = StrList.Insert(int.Parse(bb), SplitString); } //给出最后的结果 ReturnValue = StrList; //因为是正常的输出,没有错误 Error = ""; } } return ReturnValue; } #endregion ///
/// 分割字符串 /// ///
///
///
public static string[] SplitMulti(string str, string splitstr) { string[] strArray = null; if ((str != null) && (str != "")) { strArray = new Regex(splitstr).Split(str); } return strArray; } public static string SqlSafeString(string String, bool IsDel) { if (IsDel) { String = String.Replace("'", ""); String = String.Replace("\"", ""); return String; } String = String.Replace("'", "'"); String = String.Replace("\"", """); return String; } #region 获取正确的Id,如果不是正整数,返回0 ///
/// 获取正确的Id,如果不是正整数,返回0 /// ///
///
返回正确的整数ID,失败返回0
public static int StrToId(string _value) { if (IsNumberId(_value)) return int.Parse(_value); else return 0; } #endregion #region 检查一个字符串是否是纯数字构成的,一般用于查询字符串参数的有效性验证。 ///
/// 检查一个字符串是否是纯数字构成的,一般用于查询字符串参数的有效性验证。(0除外) /// ///
需验证的字符串。。 ///
是否合法的bool值。
public static bool IsNumberId(string _value) { return QuickValidate("^[1-9]*[0-9]*$", _value); } #endregion #region 快速验证一个字符串是否符合指定的正则表达式。 ///
/// 快速验证一个字符串是否符合指定的正则表达式。 /// ///
正则表达式的内容。 ///
需验证的字符串。 ///
是否合法的bool值。
public static bool QuickValidate(string _express, string _value) { if (_value == null) return false; Regex myRegex = new Regex(_express); if (_value.Length == 0) { return false; } return myRegex.IsMatch(_value); } #endregion #region 根据配置对指定字符串进行 MD5 加密 ///
/// 根据配置对指定字符串进行 MD5 加密 /// ///
///
public static string GetMD5(string s) { //md5加密 s = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(s, "md5").ToString(); return s.ToLower().Substring(8, 16); } #endregion #region 得到字符串长度,一个汉字长度为2 ///
/// 得到字符串长度,一个汉字长度为2 /// ///
参数字符串 ///
public static int StrLength(string inputString) { System.Text.ASCIIEncoding ascii = new System.Text.ASCIIEncoding(); int tempLen = 0; byte[] s = ascii.GetBytes(inputString); for (int i = 0; i < s.Length; i++) { if ((int)s[i] == 63) tempLen += 2; else tempLen += 1; } return tempLen; } #endregion #region 截取指定长度字符串 ///
/// 截取指定长度字符串 /// ///
要处理的字符串 ///
指定长度 ///
返回处理后的字符串
public static string ClipString(string inputString, int len) { bool isShowFix = false; if (len % 2 == 1) { isShowFix = true; len--; } System.Text.ASCIIEncoding ascii = new System.Text.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 (isShowFix && mybyte.Length > len) tempString += "…"; return tempString; } #endregion #region HTML转行成TEXT ///
/// HTML转行成TEXT /// ///
///
public static string HtmlToTxt(string strHtml) { string[] aryReg ={ @"
]*?>.*?", @"<(\/\s*)?!?((\w+:)?\w+)(\w+(\s*=?\s*(([""'])(\\[""'tbnr]|[^\7])*?\7|\w+)|.{0})|\s)*?(\/\s*)?>", @"([\r\n])[\s]+", @"&(quot|#34);", @"&(amp|#38);", @"&(lt|#60);", @"&(gt|#62);", @"&(nbsp|#160);", @"&(iexcl|#161);", @"&(cent|#162);", @"&(pound|#163);", @"&(copy|#169);", @"&#(\d+);", @"-->", @"
View Code

6、JS客户端输出

///     /// 客户端脚本输出    ///     public class JsHelper    {        ///         /// 弹出信息,并跳转指定页面。        ///         public static void AlertAndRedirect(string message, string toURL)        {            string js = "";            HttpContext.Current.Response.Write(string.Format(js, message, toURL));            HttpContext.Current.Response.End();        }        ///         /// 弹出信息,并返回历史页面        ///         public static void AlertAndGoHistory(string message, int value)        {            string js = @"";            HttpContext.Current.Response.Write(string.Format(js, message, value));            HttpContext.Current.Response.End();        }        ///         /// 直接跳转到指定的页面        ///         public static void Redirect(string toUrl)        {            string js = @"";            HttpContext.Current.Response.Write(string.Format(js, toUrl));        }        ///         /// 弹出信息 并指定到父窗口        ///         public static void AlertAndParentUrl(string message, string toURL)        {            string js = "";            HttpContext.Current.Response.Write(string.Format(js, message, toURL));        }        ///         /// 返回到父窗口        ///         public static void ParentRedirect(string ToUrl)        {            string js = "";            HttpContext.Current.Response.Write(string.Format(js, ToUrl));        }        ///         /// 返回历史页面        ///         public static void BackHistory(int value)        {            string js = @"";            HttpContext.Current.Response.Write(string.Format(js, value));            HttpContext.Current.Response.End();        }        ///         /// 弹出信息        ///         public static void Alert(string message)        {            string js = "";            HttpContext.Current.Response.Write(string.Format(js, message));        }        ///         /// 注册脚本块        ///         public static void RegisterScriptBlock(System.Web.UI.Page page, string _ScriptString)        {            page.ClientScript.RegisterStartupScript(page.GetType(), "scriptblock", "");        }    }
View Code

7、Cookie、Session、Cache操作

public class CookieHelper    {        ///         /// 清除指定Cookie        ///         /// cookiename        public static void ClearCookie(string cookiename)        {            HttpCookie cookie = HttpContext.Current.Request.Cookies[cookiename];            if (cookie != null)            {                cookie.Expires = DateTime.Now.AddYears(-3);                HttpContext.Current.Response.Cookies.Add(cookie);            }        }        ///         /// 获取指定Cookie值        ///         /// cookiename        /// 
public static string GetCookieValue(string cookiename) { HttpCookie cookie = HttpContext.Current.Request.Cookies[cookiename]; string str = string.Empty; if (cookie != null) { str = cookie.Value; } return str; } /// /// 添加一个Cookie(24小时过期) /// /// /// public static void SetCookie(string cookiename, string cookievalue) { SetCookie(cookiename, cookievalue, DateTime.Now.AddDays(1.0)); } /// /// 添加一个Cookie /// /// cookie名 /// cookie值 /// 过期时间 DateTime public static void SetCookie(string cookiename, string cookievalue, DateTime expires) { HttpCookie cookie = new HttpCookie(cookiename) { Value = cookievalue, Expires = expires }; HttpContext.Current.Response.Cookies.Add(cookie); } }
View Code
public static class SessionHelper2    {        ///         /// 添加Session,调动有效期为20分钟        ///         /// Session对象名称        /// Session值        public static void Add(string strSessionName, string strValue)        {            HttpContext.Current.Session[strSessionName] = strValue;            HttpContext.Current.Session.Timeout = 20;        }        ///         /// 添加Session,调动有效期为20分钟        ///         /// Session对象名称        /// Session值数组        public static void Adds(string strSessionName, string[] strValues)        {            HttpContext.Current.Session[strSessionName] = strValues;            HttpContext.Current.Session.Timeout = 20;        }        ///         /// 添加Session        ///         /// Session对象名称        /// Session值        /// 调动有效期(分钟)        public static void Add(string strSessionName, string strValue, int iExpires)        {            HttpContext.Current.Session[strSessionName] = strValue;            HttpContext.Current.Session.Timeout = iExpires;        }        ///         /// 添加Session        ///         /// Session对象名称        /// Session值数组        /// 调动有效期(分钟)        public static void Adds(string strSessionName, string[] strValues, int iExpires)        {            HttpContext.Current.Session[strSessionName] = strValues;            HttpContext.Current.Session.Timeout = iExpires;        }        ///         /// 读取某个Session对象值        ///         /// Session对象名称        /// 
Session对象值
public static string Get(string strSessionName) { if (HttpContext.Current.Session[strSessionName] == null) { return null; } else { return HttpContext.Current.Session[strSessionName].ToString(); } } /// /// 读取某个Session对象值数组 /// /// Session对象名称 ///
Session对象值数组
public static string[] Gets(string strSessionName) { if (HttpContext.Current.Session[strSessionName] == null) { return null; } else { return (string[])HttpContext.Current.Session[strSessionName]; } } /// /// 删除某个Session对象 /// /// Session对象名称 public static void Del(string strSessionName) { HttpContext.Current.Session[strSessionName] = null; } }
View Code
public class CacheHelper    {        ///         /// 获取数据缓存        ///         /// 键        public static object GetCache(string CacheKey)        {            System.Web.Caching.Cache objCache = HttpRuntime.Cache;            return objCache[CacheKey];        }        ///         /// 设置数据缓存        ///         public static void SetCache(string CacheKey, object objObject)        {            System.Web.Caching.Cache objCache = HttpRuntime.Cache;            objCache.Insert(CacheKey, objObject);        }        ///         /// 设置数据缓存        ///         public static void SetCache(string CacheKey, object objObject, TimeSpan Timeout)        {            System.Web.Caching.Cache objCache = HttpRuntime.Cache;            objCache.Insert(CacheKey, objObject, null, DateTime.MaxValue, Timeout, System.Web.Caching.CacheItemPriority.NotRemovable, null);        }        ///         /// 设置数据缓存        ///         public static void SetCache(string CacheKey, object objObject, DateTime absoluteExpiration, TimeSpan slidingExpiration)        {            System.Web.Caching.Cache objCache = HttpRuntime.Cache;            objCache.Insert(CacheKey, objObject, null, absoluteExpiration, slidingExpiration);        }        ///         /// 移除指定数据缓存        ///         public static void RemoveAllCache(string CacheKey)        {            System.Web.Caching.Cache _cache = HttpRuntime.Cache;            _cache.Remove(CacheKey);        }        ///         /// 移除全部缓存        ///         public static void RemoveAllCache()        {            System.Web.Caching.Cache _cache = HttpRuntime.Cache;            IDictionaryEnumerator CacheEnum = _cache.GetEnumerator();            while (CacheEnum.MoveNext())            {                _cache.Remove(CacheEnum.Key.ToString());            }        }    }
View Code

8、网络操作相关的类

///     /// 网络操作相关的类    ///         public class NetHelper    {        #region 检查设置的IP地址是否正确,返回正确的IP地址        ///         /// 检查设置的IP地址是否正确,并返回正确的IP地址,无效IP地址返回"-1"。        ///         /// 设置的IP地址        //public static string GetValidIP(string ip)        //{        //    if (PageValidate.IsIP(ip))        //    {        //        return ip;        //    }        //    else        //    {        //        return "-1";        //    }        //}        #endregion        #region 检查设置的端口号是否正确,返回正确的端口号        ///         /// 检查设置的端口号是否正确,并返回正确的端口号,无效端口号返回-1。        ///         /// 设置的端口号                public static int GetValidPort(string port)        {            //声明返回的正确端口号            int validPort = -1;            //最小有效端口号            const int MINPORT = 0;            //最大有效端口号            const int MAXPORT = 65535;            //检测端口号            try            {                //传入的端口号为空则抛出异常                if (port == "")                {                    throw new Exception("端口号不能为空!");                }                //检测端口范围                if ((Convert.ToInt32(port) < MINPORT) || (Convert.ToInt32(port) > MAXPORT))                {                    throw new Exception("端口号范围无效!");                }                //为端口号赋值                validPort = Convert.ToInt32(port);            }            catch (Exception ex)            {                string errMessage = ex.Message;            }            return validPort;        }        #endregion        #region 将字符串形式的IP地址转换成IPAddress对象        ///         /// 将字符串形式的IP地址转换成IPAddress对象        ///         /// 字符串形式的IP地址                public static IPAddress StringToIPAddress(string ip)        {            return IPAddress.Parse(ip);        }        #endregion        #region 获取本机的计算机名        ///         /// 获取本机的计算机名        ///         public static string LocalHostName        {            get            {                return Dns.GetHostName();            }        }        #endregion        #region 获取本机的局域网IP        ///         /// 获取本机的局域网IP        ///                 public static string LANIP        {            get            {                //获取本机的IP列表,IP列表中的第一项是局域网IP,第二项是广域网IP                IPAddress[] addressList = Dns.GetHostEntry(Dns.GetHostName()).AddressList;                //如果本机IP列表为空,则返回空字符串                if (addressList.Length < 1)                {                    return "";                }                //返回本机的局域网IP                return addressList[0].ToString();            }        }        #endregion        #region 获取本机在Internet网络的广域网IP        ///         /// 获取本机在Internet网络的广域网IP        ///                 public static string WANIP        {            get            {                //获取本机的IP列表,IP列表中的第一项是局域网IP,第二项是广域网IP                IPAddress[] addressList = Dns.GetHostEntry(Dns.GetHostName()).AddressList;                //如果本机IP列表小于2,则返回空字符串                if (addressList.Length < 2)                {                    return "";                }                //返回本机的广域网IP                return addressList[1].ToString();            }        }        #endregion        #region 获取远程客户机的IP地址        ///         /// 获取远程客户机的IP地址        ///         /// 客户端的socket对象                public static string GetClientIP(Socket clientSocket)        {            IPEndPoint client = (IPEndPoint)clientSocket.RemoteEndPoint;            return client.Address.ToString();        }        #endregion        #region 创建一个IPEndPoint对象        ///         /// 创建一个IPEndPoint对象        ///         /// IP地址        /// 端口号                public static IPEndPoint CreateIPEndPoint(string ip, int port)        {            IPAddress ipAddress = StringToIPAddress(ip);            return new IPEndPoint(ipAddress, port);        }        #endregion        #region 创建一个TcpListener对象        ///         /// 创建一个自动分配IP和端口的TcpListener对象        ///                 public static TcpListener CreateTcpListener()        {            //创建一个自动分配的网络节点            IPAddress ipAddress = IPAddress.Any;            IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 0);            return new TcpListener(localEndPoint);        }        ///         /// 创建一个TcpListener对象        ///         /// IP地址        /// 端口                public static TcpListener CreateTcpListener(string ip, int port)        {            //创建一个网络节点            IPAddress ipAddress = StringToIPAddress(ip);            IPEndPoint localEndPoint = new IPEndPoint(ipAddress, port);            return new TcpListener(localEndPoint);        }        #endregion        #region 创建一个基于TCP协议的Socket对象        ///         /// 创建一个基于TCP协议的Socket对象        ///                 public static Socket CreateTcpSocket()        {            return new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);        }        #endregion        #region 创建一个基于UDP协议的Socket对象        ///         /// 创建一个基于UDP协议的Socket对象        ///                 public static Socket CreateUdpSocket()        {            return new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);        }        #endregion        #region 获取本地终结点        #region 获取TcpListener对象的本地终结点        ///         /// 获取TcpListener对象的本地终结点        ///         /// TcpListener对象                public static IPEndPoint GetLocalPoint(TcpListener tcpListener)        {            return (IPEndPoint)tcpListener.LocalEndpoint;        }        ///         /// 获取TcpListener对象的本地终结点的IP地址        ///         /// TcpListener对象                public static string GetLocalPoint_IP(TcpListener tcpListener)        {            IPEndPoint localEndPoint = (IPEndPoint)tcpListener.LocalEndpoint;            return localEndPoint.Address.ToString();        }        ///         /// 获取TcpListener对象的本地终结点的端口号        ///         /// TcpListener对象                public static int GetLocalPoint_Port(TcpListener tcpListener)        {            IPEndPoint localEndPoint = (IPEndPoint)tcpListener.LocalEndpoint;            return localEndPoint.Port;        }        #endregion        #region 获取Socket对象的本地终结点        ///         /// 获取Socket对象的本地终结点        ///         /// Socket对象                public static IPEndPoint GetLocalPoint(Socket socket)        {            return (IPEndPoint)socket.LocalEndPoint;        }        ///         /// 获取Socket对象的本地终结点的IP地址        ///         /// Socket对象                public static string GetLocalPoint_IP(Socket socket)        {            IPEndPoint localEndPoint = (IPEndPoint)socket.LocalEndPoint;            return localEndPoint.Address.ToString();        }        ///         /// 获取Socket对象的本地终结点的端口号        ///         /// Socket对象                public static int GetLocalPoint_Port(Socket socket)        {            IPEndPoint localEndPoint = (IPEndPoint)socket.LocalEndPoint;            return localEndPoint.Port;        }        #endregion        #endregion        #region 绑定终结点        ///         /// 绑定终结点        ///         /// Socket对象        /// 要绑定的终结点        public static void BindEndPoint(Socket socket, IPEndPoint endPoint)        {            if (!socket.IsBound)            {                socket.Bind(endPoint);            }        }        ///         /// 绑定终结点        ///         /// Socket对象                /// 服务器IP地址        /// 服务器端口        public static void BindEndPoint(Socket socket, string ip, int port)        {            //创建终结点            IPEndPoint endPoint = CreateIPEndPoint(ip, port);            //绑定终结点            if (!socket.IsBound)            {                socket.Bind(endPoint);            }        }        #endregion        #region 指定Socket对象执行监听        ///         /// 指定Socket对象执行监听,默认允许的最大挂起连接数为100        ///         /// 执行监听的Socket对象        /// 监听的端口号        public static void StartListen(Socket socket, int port)        {            //创建本地终结点            IPEndPoint localPoint = CreateIPEndPoint(NetHelper.LocalHostName, port);            //绑定到本地终结点            BindEndPoint(socket, localPoint);            //开始监听            socket.Listen(100);        }        ///         /// 指定Socket对象执行监听        ///         /// 执行监听的Socket对象        /// 监听的端口号        /// 允许的最大挂起连接数        public static void StartListen(Socket socket, int port, int maxConnection)        {            //创建本地终结点            IPEndPoint localPoint = CreateIPEndPoint(NetHelper.LocalHostName, port);            //绑定到本地终结点            BindEndPoint(socket, localPoint);            //开始监听            socket.Listen(maxConnection);        }        ///         /// 指定Socket对象执行监听        ///         /// 执行监听的Socket对象        /// 监听的IP地址        /// 监听的端口号        /// 允许的最大挂起连接数        public static void StartListen(Socket socket, string ip, int port, int maxConnection)        {            //绑定到本地终结点            BindEndPoint(socket, ip, port);            //开始监听            socket.Listen(maxConnection);        }        #endregion        #region 连接到基于TCP协议的服务器        ///         /// 连接到基于TCP协议的服务器,连接成功返回true,否则返回false        ///         /// Socket对象        /// 服务器IP地址        /// 服务器端口号             public static bool Connect(Socket socket, string ip, int port)        {            try            {                //连接服务器                socket.Connect(ip, port);                //检测连接状态                return socket.Poll(-1, SelectMode.SelectWrite);            }            catch (SocketException ex)            {                throw new Exception(ex.Message);                //LogHelper.WriteTraceLog(TraceLogLevel.Error, ex.Message);            }        }        #endregion        #region 以同步方式发送消息        ///         /// 以同步方式向指定的Socket对象发送消息        ///         /// socket对象        /// 发送的消息        public static void SendMsg(Socket socket, byte[] msg)        {            //发送消息            socket.Send(msg, msg.Length, SocketFlags.None);        }        ///         /// 使用UTF8编码格式以同步方式向指定的Socket对象发送消息        ///         /// socket对象        /// 发送的消息        public static void SendMsg(Socket socket, string msg)        {            //将字符串消息转换成字符数组            byte[] buffer = ConvertHelper.StringToBytes(msg, Encoding.Default);            //发送消息            socket.Send(buffer, buffer.Length, SocketFlags.None);        }        #endregion        #region 以同步方式接收消息        ///         /// 以同步方式接收消息        ///         /// socket对象        /// 接收消息的缓冲区        public static void ReceiveMsg(Socket socket, byte[] buffer)        {            socket.Receive(buffer);        }        ///         /// 以同步方式接收消息,并转换为UTF8编码格式的字符串,使用5000字节的默认缓冲区接收。        ///         /// socket对象                public static string ReceiveMsg(Socket socket)        {            //定义接收缓冲区            byte[] buffer = new byte[5000];            //接收数据,获取接收到的字节数            int receiveCount = socket.Receive(buffer);            //定义临时缓冲区            byte[] tempBuffer = new byte[receiveCount];            //将接收到的数据写入临时缓冲区            Buffer.BlockCopy(buffer, 0, tempBuffer, 0, receiveCount);            //转换成字符串,并将其返回            return ConvertHelper.BytesToString(tempBuffer, Encoding.Default);        }        #endregion        #region 关闭基于Tcp协议的Socket对象        ///         /// 关闭基于Tcp协议的Socket对象        ///         /// 要关闭的Socket对象        public static void Close(Socket socket)        {            try            {                //禁止Socket对象接收和发送数据                socket.Shutdown(SocketShutdown.Both);            }            catch (SocketException ex)            {                throw ex;            }            finally            {                //关闭Socket对象                socket.Close();            }        }        #endregion        #region 发送电子邮件        ///         /// 发送电子邮件,所有SMTP配置信息均在config配置文件中system.net节设置.        ///         /// 接收电子邮件的地址        /// 电子邮件的标题        /// 电子邮件的正文        /// 是否开启SSL        public static bool SendEmail(string receiveEmail, string msgSubject, string msgBody, bool IsEnableSSL)        {            //创建电子邮件对象            MailMessage email = new MailMessage();            //设置接收人的电子邮件地址            email.To.Add(receiveEmail);            //设置邮件的标题            email.Subject = msgSubject;            //设置邮件的正文            email.Body = msgBody;            //设置邮件为HTML格式            email.IsBodyHtml = true;            //创建SMTP客户端,将自动从配置文件中获取SMTP服务器信息            SmtpClient smtp = new SmtpClient();            //开启SSL            smtp.EnableSsl = IsEnableSSL;            try            {                //发送电子邮件                smtp.Send(email);                return true;            }            catch (Exception ex)            {                throw ex;            }        }        #endregion    }
View Code

9、序列化操作及调用 实例

#region 序列化    public class  Serialize      {           ///         /// 序列化为对象        ///         ///         ///         public static void BinarySerialize(string objname,object obj)        {            try            {                string filename = objname + ".Binary";                if(System.IO.File.Exists(filename))                    System.IO.File.Delete(filename);                using (FileStream fileStream = new FileStream(filename, FileMode.Create))                {                    // 用二进制格式序列化                    BinaryFormatter binaryFormatter = new BinaryFormatter();                    binaryFormatter.Serialize(fileStream, obj);                    fileStream.Close();                }            }            catch(Exception ex)            {                throw new Exception(ex.Message);            }        }        ///         /// 从二进制文件中反序列化        ///         ///         /// 
public static object BinaryDeserialize(string objname) { System.Runtime.Serialization.IFormatter formatter = new BinaryFormatter(); //二进制格式反序列化 object obj; string filename = objname + ".Binary"; if(!System.IO.File.Exists(filename)) throw new Exception("在反序列化之前,请先序列化"); using (Stream stream = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read)) { obj = formatter.Deserialize(stream); stream.Close(); } //using (FileStream fs = new FileStream(filename, FileMode.Open)) //{ // BinaryFormatter formatter = new BinaryFormatter(); // object obj = formatter.Deserialize(fs); //} return obj; } /// /// 序列化为soap 即xml /// /// ///
public static void SoapSerialize(string objname,object obj) { try { string filename=objname+".Soap"; if(System.IO.File.Exists(filename)) System.IO.File.Delete(filename); using (FileStream fileStream = new FileStream(filename, FileMode.Create)) { // 序列化为Soap SoapFormatter formatter = new SoapFormatter(); formatter.Serialize(fileStream, obj); fileStream.Close(); } } catch(Exception ex) { throw new Exception(ex.Message); } } /// /// 反序列对象 /// /// public static object SoapDeserialize(string objname) { object obj; System.Runtime.Serialization.IFormatter formatter = new SoapFormatter(); string filename=objname+".Soap"; if (!System.IO.File.Exists(filename)) throw new Exception("对反序列化之前,请先序列化"); //Soap格式反序列化 using (Stream stream = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read)) { obj = formatter.Deserialize(stream); stream.Close(); } return obj; } public static void XmlSerialize(string objname,object obj) { try { string filename=objname+".xml"; if(System.IO.File.Exists(filename)) System.IO.File.Delete(filename); using (FileStream fileStream = new FileStream(filename, FileMode.Create)) { // 序列化为xml XmlSerializer formatter = new XmlSerializer(typeof(Car)); formatter.Serialize(fileStream, obj); fileStream.Close(); } } catch(Exception ex) { throw new Exception(ex.Message); } } /// /// 从xml序列中反序列化 /// /// ///
public static object XmlDeserailize(string objname) { // System.Runtime.Serialization.IFormatter formatter = new XmlSerializer(typeof(Car)); string filename=objname+".xml"; object obj; if (!System.IO.File.Exists(filename)) throw new Exception("对反序列化之前,请先序列化"); //Xml格式反序列化 using (Stream stream = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read)) { XmlSerializer formatter = new XmlSerializer(typeof(Car)); obj = (Car)formatter.Deserialize(stream); stream.Close(); } return obj; } } #endregion #region 要序列化的类 [Serializable] public class Car { private string _Price; private string _Owner; private string m_filename; [XmlElement(ElementName = "Price")] public string Price { get { return this._Price; } set { this._Price = value; } } [XmlElement(ElementName = "Owner")] public string Owner { get { return this._Owner; } set { this._Owner = value; } } public string Filename { get { return m_filename; } set { m_filename = value; } } public Car(string o, string p) { this.Price = p; this.Owner = o; } public Car() { } } #endregion #region 调用示例 public class Demo { public void DemoFunction() { //序列化 Car car = new Car("chenlin", "120万"); Serialize.BinarySerialize("Binary序列化", car); Serialize.SoapSerialize("Soap序列化", car); Serialize.XmlSerialize("XML序列化", car); //反序列化 Car car2 = (Car)Serialize.BinaryDeserialize("Binary序列化"); car2 = (Car)Serialize.SoapDeserialize("Soap序列化"); car2 = (Car)Serialize.XmlDeserailize("XML序列化"); } } #endregion
View Code

10、验证码操作,图片和数字

///     /// 验证码类    ///     public class Rand    {        #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;        }        #endregion        #region 生成随机字母与数字        ///         /// 生成随机字母与数字        ///         /// 生成长度        public static string Str(int Length)        {            return Str(Length, false);        }        ///         /// 生成随机字母与数字        ///         /// 生成长度        /// 是否要在生成前将当前线程阻止以避免重复        public static string Str(int Length, bool Sleep)        {            if (Sleep) System.Threading.Thread.Sleep(3);            char[] Pattern = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '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' };            string result = "";            int n = Pattern.Length;            System.Random random = new Random(~unchecked((int)DateTime.Now.Ticks));            for (int i = 0; i < Length; i++)            {                int rnd = random.Next(0, n);                result += Pattern[rnd];            }            return result;        }        #endregion        #region 生成随机纯字母随机数        ///         /// 生成随机纯字母随机数        ///         /// 生成长度        public static string Str_char(int Length)        {            return Str_char(Length, false);        }        ///         /// 生成随机纯字母随机数        ///         /// 生成长度        /// 是否要在生成前将当前线程阻止以避免重复        public static string Str_char(int Length, bool Sleep)        {            if (Sleep) System.Threading.Thread.Sleep(3);            char[] Pattern = new char[] { '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' };            string result = "";            int n = Pattern.Length;            System.Random random = new Random(~unchecked((int)DateTime.Now.Ticks));            for (int i = 0; i < Length; i++)            {                int rnd = random.Next(0, n);                result += Pattern[rnd];            }            return result;        }        #endregion    }    ///     /// 验证图片类    ///     public class YZMHelper    {        #region 私有字段        private string text;        private Bitmap image;        private int letterCount = 4;   //验证码位数        private int letterWidth = 16;  //单个字体的宽度范围        private int letterHeight = 20; //单个字体的高度范围        private static byte[] randb = new byte[4];        private static RNGCryptoServiceProvider rand = new RNGCryptoServiceProvider();        private Font[] fonts =     {       new Font(new FontFamily("Times New Roman"),10 +Next(1),System.Drawing.FontStyle.Regular),       new Font(new FontFamily("Georgia"), 10 + Next(1),System.Drawing.FontStyle.Regular),       new Font(new FontFamily("Arial"), 10 + Next(1),System.Drawing.FontStyle.Regular),       new Font(new FontFamily("Comic Sans MS"), 10 + Next(1),System.Drawing.FontStyle.Regular)    };        #endregion        #region 公有属性        ///         /// 验证码        ///         public string Text        {            get { return this.text; }        }        ///         /// 验证码图片        ///         public Bitmap Image        {            get { return this.image; }        }        #endregion        #region 构造函数        public YZMHelper()        {            HttpContext.Current.Response.Expires = 0;            HttpContext.Current.Response.Buffer = true;            HttpContext.Current.Response.ExpiresAbsolute = DateTime.Now.AddSeconds(-1);            HttpContext.Current.Response.AddHeader("pragma", "no-cache");            HttpContext.Current.Response.CacheControl = "no-cache";            this.text = Rand.Number(4);            CreateImage();        }        #endregion        #region 私有方法        ///         /// 获得下一个随机数        ///         /// 最大值        private static int Next(int max)        {            rand.GetBytes(randb);            int value = BitConverter.ToInt32(randb, 0);            value = value % (max + 1);            if (value < 0) value = -value;            return value;        }        ///         /// 获得下一个随机数        ///         /// 最小值        /// 最大值        private static int Next(int min, int max)        {            int value = Next(max - min) + min;            return value;        }        #endregion        #region 公共方法        ///         /// 绘制验证码        ///         public void CreateImage()        {            int int_ImageWidth = this.text.Length * letterWidth;            Bitmap image = new Bitmap(int_ImageWidth, letterHeight);            Graphics g = Graphics.FromImage(image);            g.Clear(Color.White);            for (int i = 0; i < 2; i++)            {                int x1 = Next(image.Width - 1);                int x2 = Next(image.Width - 1);                int y1 = Next(image.Height - 1);                int y2 = Next(image.Height - 1);                g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);            }            int _x = -12, _y = 0;            for (int int_index = 0; int_index < this.text.Length; int_index++)            {                _x += Next(12, 16);                _y = Next(-2, 2);                string str_char = this.text.Substring(int_index, 1);                str_char = Next(1) == 1 ? str_char.ToLower() : str_char.ToUpper();                Brush newBrush = new SolidBrush(GetRandomColor());                Point thePos = new Point(_x, _y);                g.DrawString(str_char, fonts[Next(fonts.Length - 1)], newBrush, thePos);            }            for (int i = 0; i < 10; i++)            {                int x = Next(image.Width - 1);                int y = Next(image.Height - 1);                image.SetPixel(x, y, Color.FromArgb(Next(0, 255), Next(0, 255), Next(0, 255)));            }            image = TwistImage(image, true, Next(1, 3), Next(4, 6));            g.DrawRectangle(new Pen(Color.LightGray, 1), 0, 0, int_ImageWidth - 1, (letterHeight - 1));            this.image = image;        }        ///         /// 字体随机颜色        ///         public Color GetRandomColor()        {            Random RandomNum_First = new Random((int)DateTime.Now.Ticks);            System.Threading.Thread.Sleep(RandomNum_First.Next(50));            Random RandomNum_Sencond = new Random((int)DateTime.Now.Ticks);            int int_Red = RandomNum_First.Next(180);            int int_Green = RandomNum_Sencond.Next(180);            int int_Blue = (int_Red + int_Green > 300) ? 0 : 400 - int_Red - int_Green;            int_Blue = (int_Blue > 255) ? 255 : int_Blue;            return Color.FromArgb(int_Red, int_Green, int_Blue);        }        ///         /// 正弦曲线Wave扭曲图片        ///         /// 图片路径        /// 如果扭曲则选择为True        /// 波形的幅度倍数,越大扭曲的程度越高,一般为3        /// 波形的起始相位,取值区间[0-2*PI)        public System.Drawing.Bitmap TwistImage(Bitmap srcBmp, bool bXDir, double dMultValue, double dPhase)        {            double PI = 6.283185307179586476925286766559;            Bitmap destBmp = new Bitmap(srcBmp.Width, srcBmp.Height);            Graphics graph = Graphics.FromImage(destBmp);            graph.FillRectangle(new SolidBrush(Color.White), 0, 0, destBmp.Width, destBmp.Height);            graph.Dispose();            double dBaseAxisLen = bXDir ? (double)destBmp.Height : (double)destBmp.Width;            for (int i = 0; i < destBmp.Width; i++)            {                for (int j = 0; j < destBmp.Height; j++)                {                    double dx = 0;                    dx = bXDir ? (PI * (double)j) / dBaseAxisLen : (PI * (double)i) / dBaseAxisLen;                    dx += dPhase;                    double dy = Math.Sin(dx);                    int nOldX = 0, nOldY = 0;                    nOldX = bXDir ? i + (int)(dy * dMultValue) : i;                    nOldY = bXDir ? j : j + (int)(dy * dMultValue);                    Color color = srcBmp.GetPixel(i, j);                    if (nOldX >= 0 && nOldX < destBmp.Width                     && nOldY >= 0 && nOldY < destBmp.Height)                    {                        destBmp.SetPixel(nOldX, nOldY, color);                    }                }            }            srcBmp.Dispose();            return destBmp;        }        #endregion    }
View Code

11、系统操作相关的公共类

///     /// 系统操作相关的公共类    ///         public static class SysHelper    {        #region 获取文件相对路径映射的物理路径        ///         /// 获取文件相对路径映射的物理路径        ///         /// 文件的相对路径                public static string GetPath(string virtualPath)        {            return HttpContext.Current.Server.MapPath(virtualPath);        }        #endregion               #region 获取指定调用层级的方法名        ///         /// 获取指定调用层级的方法名        ///         /// 调用的层数                public static string GetMethodName(int level)        {            //创建一个堆栈跟踪            StackTrace trace = new StackTrace();            //获取指定调用层级的方法名            return trace.GetFrame(level).GetMethod().Name;        }        #endregion        #region 获取GUID值        ///         /// 获取GUID值        ///         public static string NewGUID        {            get            {                return Guid.NewGuid().ToString();            }        }        #endregion        #region 获取换行字符        ///         /// 获取换行字符        ///         public static string NewLine        {            get            {                return Environment.NewLine;            }        }        #endregion        #region 获取当前应用程序域        ///         /// 获取当前应用程序域        ///         public static AppDomain CurrentAppDomain        {            get            {                return Thread.GetDomain();            }        }        #endregion    }
View Code

12、处理数据类型转换,数制转换、编码转换相关的类

///     /// 处理数据类型转换,数制转换、编码转换相关的类    ///         public sealed class ConvertHelper    {        #region 补足位数        ///         /// 指定字符串的固定长度,如果字符串小于固定长度,        /// 则在字符串的前面补足零,可设置的固定长度最大为9位        ///         /// 原始字符串        /// 字符串的固定长度        public static string RepairZero(string text, int limitedLength)        {            //补足0的字符串            string temp = "";            //补足0            for (int i = 0; i < limitedLength - text.Length; i++)            {                temp += "0";            }            //连接text            temp += text;            //返回补足0的字符串            return temp;        }        #endregion        #region 各进制数间转换        ///         /// 实现各进制数间的转换。ConvertBase("15",10,16)表示将十进制数15转换为16进制的数。        ///         /// 要转换的值,即原值        /// 原值的进制,只能是2,8,10,16四个值。        /// 要转换到的目标进制,只能是2,8,10,16四个值。        public static string ConvertBase(string value, int from, int to)        {            try            {                int intValue = Convert.ToInt32(value, from);  //先转成10进制                string result = Convert.ToString(intValue, to);  //再转成目标进制                if (to == 2)                {                    int resultLength = result.Length;  //获取二进制的长度                    switch (resultLength)                    {                        case 7:                            result = "0" + result;                            break;                        case 6:                            result = "00" + result;                            break;                        case 5:                            result = "000" + result;                            break;                        case 4:                            result = "0000" + result;                            break;                        case 3:                            result = "00000" + result;                            break;                    }                }                return result;            }            catch            {                //LogHelper.WriteTraceLog(TraceLogLevel.Error, ex.Message);                return "0";            }        }        #endregion        #region 使用指定字符集将string转换成byte[]        ///         /// 使用指定字符集将string转换成byte[]        ///         /// 要转换的字符串        /// 字符编码        public static byte[] StringToBytes(string text, Encoding encoding)        {            return encoding.GetBytes(text);        }        #endregion        #region 使用指定字符集将byte[]转换成string        ///         /// 使用指定字符集将byte[]转换成string        ///         /// 要转换的字节数组        /// 字符编码        public static string BytesToString(byte[] bytes, Encoding encoding)        {            return encoding.GetString(bytes);        }        #endregion        #region 将byte[]转换成int        ///         /// 将byte[]转换成int        ///         /// 需要转换成整数的byte数组        public static int BytesToInt32(byte[] data)        {            //如果传入的字节数组长度小于4,则返回0            if (data.Length < 4)            {                return 0;            }            //定义要返回的整数            int num = 0;            //如果传入的字节数组长度大于4,需要进行处理            if (data.Length >= 4)            {                //创建一个临时缓冲区                byte[] tempBuffer = new byte[4];                //将传入的字节数组的前4个字节复制到临时缓冲区                Buffer.BlockCopy(data, 0, tempBuffer, 0, 4);                //将临时缓冲区的值转换成整数,并赋给num                num = BitConverter.ToInt32(tempBuffer, 0);            }            //返回整数            return num;        }        #endregion    }
View Code

 

好了,本文主要为了整合网上资源及个人开发过程中的一些常用类,方便开发过程中快速查找。暂且列举这么些,后续慢慢添加

 

转载于:https://www.cnblogs.com/nyzhai/p/3317141.html

你可能感兴趣的文章
c++类的嵌套(1)
查看>>
Android SqlLite数据库的创建、增、删、改、查、使用事务
查看>>
phpStorm无法使用svn1.8的解决办法
查看>>
Talk is cheap,show me the code
查看>>
[Java]知乎下巴第3集:来人啊快把知乎的答案装到篮子里去
查看>>
解决中文乱码的问题
查看>>
前端异常测试
查看>>
JSON与localStorage的爱恨情仇
查看>>
input验证码框,输入非数字或非12位时,红框提示;每4位加一个空格
查看>>
IOS上iframe的滚动条失效的解决办法
查看>>
C++_012C++11的语法新特性
查看>>
Git学习笔记:常用命令总结
查看>>
iOS - OC 与 Swift 互相操作
查看>>
sort、qsort排序
查看>>
修改时无论改成什么,值总是默认为1
查看>>
Android自动化测试01-环境安装连接问题及解决
查看>>
zencart后台修改首页meta_title、meta_keywords、meta_description
查看>>
SecureCRT 常用命令大全
查看>>
Android 通过触摸动态地在屏幕上画矩形
查看>>
序列化 反序列化
查看>>