web开发过程中经常用到的一些公共方法及操作

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

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

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

页面框架设计如下:

<div id="tabs">
<ul>
<li><a href="#tabs-1">基本信息</a></li>
<li runat="server" id="li2"><a href="#tabs-2">风险点类型</a></li>
</ul>
<div id="tabs-1">
<iframe id="Iframe1" src="" style="width: 100%; height: 521px;" runat="server" frameborder="0">
</iframe>
</div>
<div id="tabs-2">
<iframe id="Iframe2" src="" style="width: 100%; height: 521px;" runat="server" frameborder="0">
</iframe>
</div>
</div>

其中一个子页面在后台添加成功之后让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 私有方法
/// <summary>
/// 过滤特殊字符
/// </summary>
private static string String2Json(String s)
{
StringBuilder sb = new StringBuilder();
for (int i = ; 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();
} /// <summary>
/// 格式化字符型、日期型、布尔型
/// </summary>
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
/// <summary>
/// List转换成Json
/// </summary>
public static string ListToJson<T>(IList<T> list)
{
object obj = list[];
return ListToJson<T>(list, obj.GetType().Name);
} /// <summary>
/// List转换成Json
/// </summary>
public static string ListToJson<T>(IList<T> list, string jsonName)
{
StringBuilder Json = new StringBuilder();
if (string.IsNullOrEmpty(jsonName)) jsonName = list[].GetType().Name;
Json.Append("{\"" + jsonName + "\":[");
if (list.Count > )
{
for (int i = ; i < list.Count; i++)
{
T obj = Activator.CreateInstance<T>();
PropertyInfo[] pi = obj.GetType().GetProperties();
Json.Append("{");
for (int j = ; 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 - )
{
Json.Append(",");
}
}
Json.Append("}");
if (i < list.Count - )
{
Json.Append(",");
}
}
}
Json.Append("]}");
return Json.ToString();
}
#endregion #region 对象转换为Json
/// <summary>
/// 对象转换为Json
/// </summary>
/// <param name="jsonObject">对象</param>
/// <returns>Json字符串</returns>
public static string ToJson(object jsonObject)
{
string jsonString = "{";
PropertyInfo[] propertyInfo = jsonObject.GetType().GetProperties();
for (int i = ; 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 - , jsonString.Length);
return jsonString + "}";
}
#endregion #region 对象集合转换Json
/// <summary>
/// 对象集合转换Json
/// </summary>
/// <param name="array">集合对象</param>
/// <returns>Json字符串</returns>
public static string ToJson(IEnumerable array)
{
string jsonString = "[";
foreach (object item in array)
{
jsonString += ToJson(item) + ",";
}
jsonString.Remove(jsonString.Length - , jsonString.Length);
return jsonString + "]";
}
#endregion #region 普通集合转换Json
/// <summary>
/// 普通集合转换Json
/// </summary>
/// <param name="array">集合对象</param>
/// <returns>Json字符串</returns>
public static string ToArrayString(IEnumerable array)
{
string jsonString = "[";
foreach (object item in array)
{
jsonString = ToJson(item.ToString()) + ",";
}
jsonString.Remove(jsonString.Length - , jsonString.Length);
return jsonString + "]";
}
#endregion #region DataSet转换为Json
/// <summary>
/// DataSet转换为Json
/// </summary>
/// <param name="dataSet">DataSet对象</param>
/// <returns>Json字符串</returns>
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
/// <summary>
/// Datatable转换为Json
/// </summary>
/// <param name="table">Datatable对象</param>
/// <returns>Json字符串</returns>
public static string ToJson(DataTable dt)
{
StringBuilder jsonString = new StringBuilder();
jsonString.Append("[");
DataRowCollection drc = dt.Rows;
for (int i = ; i < drc.Count; i++)
{
jsonString.Append("{");
for (int j = ; 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 - )
{
jsonString.Append(strValue + ",");
}
else
{
jsonString.Append(strValue);
}
}
jsonString.Append("},");
}
jsonString.Remove(jsonString.Length - , );
jsonString.Append("]");
return jsonString.ToString();
} /// <summary>
/// DataTable转换为Json
/// </summary>
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 > )
{
for (int i = ; i < dt.Rows.Count; i++)
{
Json.Append("{");
for (int j = ; 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 - )
{
Json.Append(",");
}
}
Json.Append("}");
if (i < dt.Rows.Count - )
{
Json.Append(",");
}
}
}
Json.Append("]}");
return Json.ToString();
}
#endregion #region DataReader转换为Json
/// <summary>
/// DataReader转换为Json
/// </summary>
/// <param name="dataReader">DataReader对象</param>
/// <returns>Json字符串</returns>
public static string ToJson(DbDataReader dataReader)
{
StringBuilder jsonString = new StringBuilder();
jsonString.Append("[");
while (dataReader.Read())
{
jsonString.Append("{");
for (int i = ; 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 - )
{
jsonString.Append(strValue + ",");
}
else
{
jsonString.Append(strValue);
}
}
jsonString.Append("},");
}
dataReader.Close();
jsonString.Remove(jsonString.Length - , );
jsonString.Append("]");
return jsonString.ToString();
}
#endregion

2、XML操作类

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

3、文件下载

public class FileDown
{
public FileDown()
{ } /// <summary>
/// 参数为虚拟路径
/// </summary>
public static string FileNameExtension(string FileName)
{
return Path.GetExtension(MapPathFile(FileName));
} /// <summary>
/// 获取物理地址
/// </summary>
public static string MapPathFile(string FileName)
{
return HttpContext.Current.Server.MapPath(FileName);
} /// <summary>
/// 普通下载
/// </summary>
/// <param name="FileName">文件虚拟路径</param>
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();
}
} /// <summary>
/// 分块下载
/// </summary>
/// <param name="FileName">文件虚拟路径</param>
public static void DownLoad(string FileName)
{
string filePath = MapPathFile(FileName);
long chunkSize = ; //指定块大小
byte[] buffer = new byte[chunkSize]; //建立一个200K的缓冲区
long dataToRead = ; //已读的字节数
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 > )
{
if (HttpContext.Current.Response.IsClientConnected)
{
int length = stream.Read(buffer, , Convert.ToInt32(chunkSize));
HttpContext.Current.Response.OutputStream.Write(buffer, , length);
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.Clear();
dataToRead -= length;
}
else
{
dataToRead = -; //防止client失去连接
}
}
}
catch (Exception ex)
{
HttpContext.Current.Response.Write("Error:" + ex.Message);
}
finally
{
if (stream != null) stream.Close();
HttpContext.Current.Response.Close();
}
} /// <summary>
/// 输出硬盘文件,提供下载 支持大文件、续传、速度限制、资源占用小
/// </summary>
/// <param name="_Request">Page.Request对象</param>
/// <param name="_Response">Page.Response对象</param>
/// <param name="_fileName">下载文件名</param>
/// <param name="_fullPath">带文件名下载路径</param>
/// <param name="_speed">每秒允许下载的字节数</param>
/// <returns>返回是否成功</returns>
//---------------------------------------------------------------------
//调用:
// 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 = ;
int pack = ; //10K bytes
int sleep = (int)Math.Floor((double)( * pack / _speed)) + ; if (_Request.Headers["Range"] != null)
{
_Response.StatusCode = ;
string[] range = _Request.Headers["Range"].Split(new char[] { '=', '-' });
startBytes = Convert.ToInt64(range[]);
}
_Response.AddHeader("Content-Length", (fileLength - startBytes).ToString());
if (startBytes != )
{
_Response.AddHeader("Content-Range", string.Format(" bytes {0}-{1}/{2}", startBytes, fileLength - , 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)) + ; for (int i = ; 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;
}
}

4、ResponseFile输出下载

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

public class DownLoadHelper
{
#region ResponseFile 输出硬盘文件,提供下载 支持大文件、续传、速度限制、资源占用小
/// <summary>
/// 输出硬盘文件,提供下载 支持大文件、续传、速度限制、资源占用小
/// </summary>
/// <param name="_Request">Page.Request对象</param>
/// <param name="_Response">Page.Response对象</param>
/// <param name="_fileName">下载文件名</param>
/// <param name="_fullPath">带文件名下载路径</param>
/// <param name="_speed">每秒允许下载的字节数</param>
/// <returns>返回是否成功</returns>
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 = ; int pack = ; //10K bytes
//int sleep = 200; //每秒5次 即5*10K bytes每秒
int sleep = (int)Math.Floor((double)( * pack / _speed)) + ;
if (_Request.Headers["Range"] != null)
{
_Response.StatusCode = ;
string[] range = _Request.Headers["Range"].Split(new char[] { '=', '-' });
startBytes = Convert.ToInt64(range[]);
}
_Response.AddHeader("Content-Length", (fileLength - startBytes).ToString());
if (startBytes != )
{
_Response.AddHeader("Content-Range", string.Format(" bytes {0}-{1}/{2}", startBytes, fileLength - , 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)) + ; for (int i = ; 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
}

5、字符串操作

/// <summary>
/// 字符串操作类
/// 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<int, int> 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)
/// </summary>
public class StringHelper
{
/// <summary>
/// 把字符串按照分隔符转换成 List
/// </summary>
/// <param name="str">源字符串</param>
/// <param name="speater">分隔符</param>
/// <param name="toLower">是否转换为小写</param>
/// <returns></returns>
public static List<string> GetStrArray(string str, char speater, bool toLower)
{
List<string> list = new List<string>();
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;
}
/// <summary>
/// 把字符串转 按照, 分割 换为数据
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static string[] GetStrArray(string str)
{
return str.Split(new Char[] { ',' });
}
/// <summary>
/// 把 List<string> 按照分隔符组装成 string
/// </summary>
/// <param name="list"></param>
/// <param name="speater"></param>
/// <returns></returns>
public static string GetArrayStr(List<string> list, string speater)
{
StringBuilder sb = new StringBuilder();
for (int i = ; i < list.Count; i++)
{
if (i == list.Count - )
{
sb.Append(list[i]);
}
else
{
sb.Append(list[i]);
sb.Append(speater);
}
}
return sb.ToString();
}
/// <summary>
/// 得到数组列表以逗号分隔的字符串
/// </summary>
/// <param name="list"></param>
/// <returns></returns>
public static string GetArrayStr(List<int> list)
{
StringBuilder sb = new StringBuilder();
for (int i = ; i < list.Count; i++)
{
if (i == list.Count - )
{
sb.Append(list[i].ToString());
}
else
{
sb.Append(list[i]);
sb.Append(",");
}
}
return sb.ToString();
}
/// <summary>
/// 得到数组列表以逗号分隔的字符串
/// </summary>
/// <param name="list"></param>
/// <returns></returns>
public static string GetArrayValueStr(Dictionary<int, int> list)
{
StringBuilder sb = new StringBuilder();
foreach (KeyValuePair<int, int> kvp in list)
{
sb.Append(kvp.Value + ",");
}
if (list.Count > )
{
return DelLastComma(sb.ToString());
}
else
{
return "";
}
} #region 删除最后一个字符之后的字符 /// <summary>
/// 删除最后结尾的一个逗号
/// </summary>
public static string DelLastComma(string str)
{
return str.Substring(, str.LastIndexOf(","));
} /// <summary>
/// 删除最后结尾的指定字符后的字符
/// </summary>
public static string DelLastChar(string str, string strchar)
{
return str.Substring(, str.LastIndexOf(strchar));
} #endregion /// <summary>
/// 转全角的函数(SBC case)
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public static string ToSBC(string input)
{
//半角转全角:
char[] c = input.ToCharArray();
for (int i = ; i < c.Length; i++)
{
if (c[i] == )
{
c[i] = (char);
continue;
}
if (c[i] < )
c[i] = (char)(c[i] + );
}
return new string(c);
} /// <summary>
/// 转半角的函数(SBC case)
/// </summary>
/// <param name="input">输入</param>
/// <returns></returns>
public static string ToDBC(string input)
{
char[] c = input.ToCharArray();
for (int i = ; i < c.Length; i++)
{
if (c[i] == )
{
c[i] = (char);
continue;
}
if (c[i] > && c[i] < )
c[i] = (char)(c[i] - );
}
return new string(c);
} /// <summary>
/// 把字符串按照指定分隔符装成 List 去除重复
/// </summary>
/// <param name="o_str"></param>
/// <param name="sepeater"></param>
/// <returns></returns>
public static List<string> GetSubStringList(string o_str, char sepeater)
{
List<string> list = new List<string>();
string[] ss = o_str.Split(sepeater);
foreach (string s in ss)
{
if (!string.IsNullOrEmpty(s) && s != sepeater.ToString())
{
list.Add(s);
}
}
return list;
} #region 将字符串样式转换为纯字符串
/// <summary>
/// 将字符串样式转换为纯字符串
/// </summary>
/// <param name="StrList"></param>
/// <param name="SplitString"></param>
/// <returns></returns>
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 将字符串转换为新样式
/// <summary>
/// 将字符串转换为新样式
/// </summary>
/// <param name="StrList"></param>
/// <param name="NewStyle"></param>
/// <param name="SplitString"></param>
/// <param name="Error"></param>
/// <returns></returns>
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 = ; i < NewStyle.Length; i++)
{
if (NewStyle.Substring(i, ) == SplitString)
{
Lengstr = Lengstr + "," + i;
}
}
if (Lengstr != "")
{
Lengstr = Lengstr.Substring();
}
//将分隔符放在新样式中的位置
string[] str = Lengstr.Split(',');
foreach (string bb in str)
{
StrList = StrList.Insert(int.Parse(bb), SplitString);
}
//给出最后的结果
ReturnValue = StrList;
//因为是正常的输出,没有错误
Error = "";
}
}
return ReturnValue;
}
#endregion /// <summary>
/// 分割字符串
/// </summary>
/// <param name="str"></param>
/// <param name="splitstr"></param>
/// <returns></returns>
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
/// <summary>
/// 获取正确的Id,如果不是正整数,返回0
/// </summary>
/// <param name="_value"></param>
/// <returns>返回正确的整数ID,失败返回0</returns>
public static int StrToId(string _value)
{
if (IsNumberId(_value))
return int.Parse(_value);
else
return ;
}
#endregion
#region 检查一个字符串是否是纯数字构成的,一般用于查询字符串参数的有效性验证。
/// <summary>
/// 检查一个字符串是否是纯数字构成的,一般用于查询字符串参数的有效性验证。(0除外)
/// </summary>
/// <param name="_value">需验证的字符串。。</param>
/// <returns>是否合法的bool值。</returns>
public static bool IsNumberId(string _value)
{
return QuickValidate("^[1-9]*[0-9]*$", _value);
}
#endregion
#region 快速验证一个字符串是否符合指定的正则表达式。
/// <summary>
/// 快速验证一个字符串是否符合指定的正则表达式。
/// </summary>
/// <param name="_express">正则表达式的内容。</param>
/// <param name="_value">需验证的字符串。</param>
/// <returns>是否合法的bool值。</returns>
public static bool QuickValidate(string _express, string _value)
{
if (_value == null) return false;
Regex myRegex = new Regex(_express);
if (_value.Length == )
{
return false;
}
return myRegex.IsMatch(_value);
}
#endregion #region 根据配置对指定字符串进行 MD5 加密
/// <summary>
/// 根据配置对指定字符串进行 MD5 加密
/// </summary>
/// <param name="s"></param>
/// <returns></returns>
public static string GetMD5(string s)
{
//md5加密
s = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(s, "md5").ToString(); return s.ToLower().Substring(, );
}
#endregion #region 得到字符串长度,一个汉字长度为2
/// <summary>
/// 得到字符串长度,一个汉字长度为2
/// </summary>
/// <param name="inputString">参数字符串</param>
/// <returns></returns>
public static int StrLength(string inputString)
{
System.Text.ASCIIEncoding ascii = new System.Text.ASCIIEncoding();
int tempLen = ;
byte[] s = ascii.GetBytes(inputString);
for (int i = ; i < s.Length; i++)
{
if ((int)s[i] == )
tempLen += ;
else
tempLen += ;
}
return tempLen;
}
#endregion #region 截取指定长度字符串
/// <summary>
/// 截取指定长度字符串
/// </summary>
/// <param name="inputString">要处理的字符串</param>
/// <param name="len">指定长度</param>
/// <returns>返回处理后的字符串</returns>
public static string ClipString(string inputString, int len)
{
bool isShowFix = false;
if (len % == )
{
isShowFix = true;
len--;
}
System.Text.ASCIIEncoding ascii = new System.Text.ASCIIEncoding();
int tempLen = ;
string tempString = "";
byte[] s = ascii.GetBytes(inputString);
for (int i = ; i < s.Length; i++)
{
if ((int)s[i] == )
tempLen += ;
else
tempLen += ; try
{
tempString += inputString.Substring(i, );
}
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
/// <summary>
/// HTML转行成TEXT
/// </summary>
/// <param name="strHtml"></param>
/// <returns></returns>
public static string HtmlToTxt(string strHtml)
{
string[] aryReg ={
@"<script[^>]*?>.*?</script>",
@"<(\/\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+);",
@"-->",
@"<!--.*\n"
}; string newReg = aryReg[];
string strOutput = strHtml;
for (int i = ; i < aryReg.Length; i++)
{
Regex regex = new Regex(aryReg[i], RegexOptions.IgnoreCase);
strOutput = regex.Replace(strOutput, string.Empty);
} strOutput.Replace("<", "");
strOutput.Replace(">", "");
strOutput.Replace("\r\n", ""); return strOutput;
}
#endregion #region 判断对象是否为空
/// <summary>
/// 判断对象是否为空,为空返回true
/// </summary>
/// <typeparam name="T">要验证的对象的类型</typeparam>
/// <param name="data">要验证的对象</param>
public static bool IsNullOrEmpty<T>(T data)
{
//如果为null
if (data == null)
{
return true;
} //如果为""
if (data.GetType() == typeof(String))
{
if (string.IsNullOrEmpty(data.ToString().Trim()))
{
return true;
}
} //如果为DBNull
if (data.GetType() == typeof(DBNull))
{
return true;
} //不为空
return false;
} /// <summary>
/// 判断对象是否为空,为空返回true
/// </summary>
/// <param name="data">要验证的对象</param>
public static bool IsNullOrEmpty(object data)
{
//如果为null
if (data == null)
{
return true;
} //如果为""
if (data.GetType() == typeof(String))
{
if (string.IsNullOrEmpty(data.ToString().Trim()))
{
return true;
}
} //如果为DBNull
if (data.GetType() == typeof(DBNull))
{
return true;
} //不为空
return false;
}
#endregion
}

6、JS客户端输出

  /// <summary>
/// 客户端脚本输出
/// </summary>
public class JsHelper
{
/// <summary>
/// 弹出信息,并跳转指定页面。
/// </summary>
public static void AlertAndRedirect(string message, string toURL)
{
string js = "<script language=javascript>alert('{0}');window.location.replace('{1}')</script>";
HttpContext.Current.Response.Write(string.Format(js, message, toURL));
HttpContext.Current.Response.End();
} /// <summary>
/// 弹出信息,并返回历史页面
/// </summary>
public static void AlertAndGoHistory(string message, int value)
{
string js = @"<Script language='JavaScript'>alert('{0}');history.go({1});</Script>";
HttpContext.Current.Response.Write(string.Format(js, message, value));
HttpContext.Current.Response.End();
} /// <summary>
/// 直接跳转到指定的页面
/// </summary>
public static void Redirect(string toUrl)
{
string js = @"<script language=javascript>window.location.replace('{0}')</script>";
HttpContext.Current.Response.Write(string.Format(js, toUrl));
} /// <summary>
/// 弹出信息 并指定到父窗口
/// </summary>
public static void AlertAndParentUrl(string message, string toURL)
{
string js = "<script language=javascript>alert('{0}');window.top.location.replace('{1}')</script>";
HttpContext.Current.Response.Write(string.Format(js, message, toURL));
} /// <summary>
/// 返回到父窗口
/// </summary>
public static void ParentRedirect(string ToUrl)
{
string js = "<script language=javascript>window.top.location.replace('{0}')</script>";
HttpContext.Current.Response.Write(string.Format(js, ToUrl));
} /// <summary>
/// 返回历史页面
/// </summary>
public static void BackHistory(int value)
{
string js = @"<Script language='JavaScript'>history.go({0});</Script>";
HttpContext.Current.Response.Write(string.Format(js, value));
HttpContext.Current.Response.End();
} /// <summary>
/// 弹出信息
/// </summary>
public static void Alert(string message)
{
string js = "<script language=javascript>alert('{0}');</script>";
HttpContext.Current.Response.Write(string.Format(js, message));
} /// <summary>
/// 注册脚本块
/// </summary>
public static void RegisterScriptBlock(System.Web.UI.Page page, string _ScriptString)
{
page.ClientScript.RegisterStartupScript(page.GetType(), "scriptblock", "<script type='text/javascript'>" + _ScriptString + "</script>");
}
}

7、Cookie、Session、Cache操作

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

8、网络操作相关的类

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

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

 #region 序列化
public class Serialize
{
/// <summary>
/// 序列化为对象
/// </summary>
/// <param name="objname"></param>
/// <param name="obj"></param>
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);
}
} /// <summary>
/// 从二进制文件中反序列化
/// </summary>
/// <param name="objname"></param>
/// <returns></returns>
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; } /// <summary>
/// 序列化为soap 即xml
/// </summary>
/// <param name="objname"></param>
/// <returns></returns>
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);
}
} /// <summary>
/// 反序列对象
/// </summary>
/// <param name="objname"></param>
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);
} } /// <summary>
/// 从xml序列中反序列化
/// </summary>
/// <param name="objname"></param>
/// <returns></returns>
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

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

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

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

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

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

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

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

上一篇:J2EE项目开发中常用到的公共方法


下一篇:iOS常用公共方法