目录
1.DataTable帮助类
2.DbhelperOleDb类
3.SearchCondition 类
4. Html操作类
5.HtmlPager 类
6.HtmlUtils类
首先大家在工作以后都会总结一下自己常用的工具类。
这里分享下我的工具类:
下面开始挨个介绍:
using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using System.Data;
using System.Collections;
namespace Core.DBUtility
{
///
/// DataTable帮助类
///
public class DataTableHelper
{
///
/// 给DataTable增加一个自增列
/// 如果DataTable 存在 identityid 字段 则 直接返回DataTable 不做任何处理
///
/// DataTable
/// 返回Datatable 增加字段 identityid
public static DataTable AddIdentityColumn(DataTable dt)
{
if (!dt.Columns.Contains("identityid"))
{
dt.Columns.Add("identityid");
for (int i = 0; i < dt.Rows.Count; i++)
{
dt.Rows[i]["identityid"] = (i + 1).ToString();
}
}
return dt;
}
///
/// 检查DataTable 是否有数据行
///
/// DataTable
///
public static bool IsHaveRows(DataTable dt)
{
if (dt != null && dt.Rows.Count > 0)
return true;
return false;
}
///
/// DataTable转换成实体列表
///
/// 实体 T
/// datatable
///
public static IList DataTableToList(DataTable table)
where T : class
{
if (!IsHaveRows(table))
return new List();
IList list = new List();
T model = default(T);
foreach (DataRow dr in table.Rows)
{
model = Activator.CreateInstance();
foreach (DataColumn dc in dr.Table.Columns)
{
object drValue = dr[dc.ColumnName];
PropertyInfo pi = model.GetType().GetProperty(dc.ColumnName);
if (pi != null && pi.CanWrite && (drValue != null && !Convert.IsDBNull(drValue)))
{
pi.SetValue(model, drValue, null);
}
}
list.Add(model);
}
return list;
}
///
/// 实体列表转换成DataTable
///
/// 实体
/// 实体列表
///
public static DataTable ListToDataTable(IList list)
where T : class
{
if (list == null || list.Count <= 0)
{
return null;
}
DataTable dt = new DataTable(typeof(T).Name);
DataColumn column;
DataRow row;
PropertyInfo[] myPropertyInfo = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
int length = myPropertyInfo.Length;
bool createColumn = true;
foreach (T t in list)
{
if (t == null)
{
continue;
}
row = dt.NewRow();
for (int i = 0; i < length; i++)
{
PropertyInfo pi = myPropertyInfo[i];
string name = pi.Name;
if (createColumn)
{
column = new DataColumn(name, pi.PropertyType);
dt.Columns.Add(column);
}
row[name] = pi.GetValue(t, null);
}
if (createColumn)
{
createColumn = false;
}
dt.Rows.Add(row);
}
return dt;
}
///
/// 将泛型集合类转换成DataTable
///
/// 集合项类型
/// 集合
/// 数据集(表)
public static DataTable ToDataTable(IList list)
{
return ToDataTable(list, null);
}
///
/// 将泛型集合类转换成DataTable
///
/// 集合项类型
/// 集合
/// 需要返回的列的列名
/// 数据集(表)
public static DataTable ToDataTable(IList list, params string[] propertyName)
{
List propertyNameList = new List();
if (propertyName != null)
propertyNameList.AddRange(propertyName);
DataTable result = new DataTable();
if (list.Count > 0)
{
PropertyInfo[] propertys = list[0].GetType().GetProperties();
foreach (PropertyInfo pi in propertys)
{
if (propertyNameList.Count == 0)
{
result.Columns.Add(pi.Name, pi.PropertyType);
}
else
{
if (propertyNameList.Contains(pi.Name))
{
result.Columns.Add(pi.Name, pi.PropertyType);
}
}
}
for (int i = 0; i < list.Count; i++)
{
ArrayList tempList = new ArrayList();
foreach (PropertyInfo pi in propertys)
{
if (propertyNameList.Count == 0)
{
object obj = pi.GetValue(list[i], null);
tempList.Add(obj);
}
else
{
if (propertyNameList.Contains(pi.Name))
{
object obj = pi.GetValue(list[i], null);
tempList.Add(obj);
}
}
}
object[] array = tempList.ToArray();
result.LoadDataRow(array, true);
}
}
return result;
}
///
/// 根据nameList里面的字段创建一个表格,返回该表格的DataTable
///
/// 包含字段信息的列表
/// DataTable
public static DataTable CreateTable(List nameList)
{
if (nameList.Count <= 0)
return null;
DataTable myDataTable = new DataTable();
foreach (string columnName in nameList)
{
myDataTable.Columns.Add(columnName, typeof(string));
}
return myDataTable;
}
///
/// 通过字符列表创建表字段,字段格式可以是:
/// 1) a,b,c,d,e
/// 2) a|int,b|string,c|bool,d|decimal
///
///
///
public static DataTable CreateTable(string nameString)
{
string[] nameArray = nameString.Split(new char[] { ',', ';' });
List nameList = new List();
DataTable dt = new DataTable();
foreach (string item in nameArray)
{
if (!string.IsNullOrEmpty(item))
{
string[] subItems = item.Split('|');
if (subItems.Length == 2)
{
dt.Columns.Add(subItems[0], ConvertType(subItems[1]));
}
else
{
dt.Columns.Add(subItems[0]);
}
}
}
return dt;
}
private static Type ConvertType(string typeName)
{
typeName = typeName.ToLower().Replace("system.", "");
Type newType = typeof(string);
switch (typeName)
{
case "boolean":
case "bool":
newType = typeof(bool);
break;
case "int16":
case "short":
newType = typeof(short);
break;
case "int32":
case "int":
newType = typeof(int);
break;
case "long":
case "int64":
newType = typeof(long);
break;
case "uint16":
case "ushort":
newType = typeof(ushort);
break;
case "uint32":
case "uint":
newType = typeof(uint);
break;
case "uint64":
case "ulong":
newType = typeof(ulong);
break;
case "single":
case "float":
newType = typeof(float);
break;
case "string":
newType = typeof(string);
break;
case "guid":
newType = typeof(Guid);
break;
case "decimal":
newType = typeof(decimal);
break;
case "double":
newType = typeof(double);
break;
case "datetime":
newType = typeof(DateTime);
break;
case "byte":
newType = typeof(byte);
break;
case "char":
newType = typeof(char);
break;
}
return newType;
}
///
/// 获得从DataRowCollection转换成的DataRow数组
///
/// DataRowCollection
///
public static DataRow[] GetDataRowArray(DataRowCollection drc)
{
int count = drc.Count;
DataRow[] drs = new DataRow[count];
for (int i = 0; i < count; i++)
{
drs[i] = drc[i];
}
return drs;
}
///
/// 将DataRow数组转换成DataTable,注意行数组的每个元素须具有相同的数据结构,
/// 否则当有元素长度大于第一个元素时,抛出异常
///
/// 行数组
///
public static DataTable GetTableFromRows(DataRow[] rows)
{
if (rows.Length <= 0)
{
return new DataTable();
}
DataTable dt = rows[0].Table.Clone();
dt.DefaultView.Sort = rows[0].Table.DefaultView.Sort;
for (int i = 0; i < rows.Length; i++)
{
dt.LoadDataRow(rows[i].ItemArray, true);
}
return dt;
}
///
/// 排序表的视图
///
///
///
///
public static DataTable SortedTable(DataTable dt, params string[] sorts)
{
if (dt.Rows.Count > 0)
{
string tmp = "";
for (int i = 0; i < sorts.Length; i++)
{
tmp += sorts[i] + ",";
}
dt.DefaultView.Sort = tmp.TrimEnd(',');
}
return dt;
}
///
/// 根据条件过滤表的内容
///
///
///
///
public static DataTable FilterDataTable(DataTable dt, string condition)
{
if (condition.Trim() == "")
{
return dt;
}
else
{
DataTable newdt = new DataTable();
newdt = dt.Clone();
DataRow[] dr = dt.Select(condition);
for (int i = 0; i < dr.Length; i++)
{
newdt.ImportRow((DataRow)dr[i]);
}
return newdt;
}
}
}
}
using System;
using System.Collections;
using System.Data;
using System.Data.OleDb;
namespace Core.DBUtility
{
///
/// Copyright (C) 2004-2008 LiTianPing
/// 数据访问基础类(基于OleDb)
/// 可以用户可以修改满足自己项目的需要。
///
public abstract class DbHelperOleDb
{
//数据库连接字符串(web.config来配置),可以动态更改connectionString支持多数据库.
public static string connectionString = "";// PubConstant.ConnectionString;
public DbHelperOleDb()
{
}
#region 公用方法
public static int GetMaxID(string FieldName, string TableName)
{
string strsql = "select max(" + FieldName + ")+1 from " + TableName;
object obj = GetSingle(strsql);
if (obj == null)
{
return 1;
}
else
{
return int.Parse(obj.ToString());
}
}
public static bool Exists(string strSql)
{
object obj = GetSingle(strSql);
int cmdresult;
if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
{
cmdresult = 0;
}
else
{
cmdresult = int.Parse(obj.ToString());
}
if (cmdresult == 0)
{
return false;
}
else
{
return true;
}
}
public static bool Exists(string strSql, params OleDbParameter[] cmdParms)
{
object obj = GetSingle(strSql, cmdParms);
int cmdresult;
if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
{
cmdresult = 0;
}
else
{
cmdresult = int.Parse(obj.ToString());
}
if (cmdresult == 0)
{
return false;
}
else
{
return true;
}
}
#endregion
#region 执行简单SQL语句
///
/// 执行SQL语句,返回影响的记录数
///
/// SQL语句
/// 影响的记录数
public static int ExecuteSql(string SQLString)
{
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
using (OleDbCommand cmd = new OleDbCommand(SQLString, connection))
{
try
{
connection.Open();
int rows = cmd.ExecuteNonQuery();
return rows;
}
catch (System.Data.OleDb.OleDbException E)
{
connection.Close();
throw new Exception(E.Message);
}
}
}
}
///
/// 执行多条SQL语句,实现数据库事务。
///
/// 多条SQL语句
public static void ExecuteSqlTran(ArrayList SQLStringList)
{
using (OleDbConnection conn = new OleDbConnection(connectionString))
{
conn.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = conn;
OleDbTransaction tx = conn.BeginTransaction();
cmd.Transaction = tx;
try
{
for (int n = 0; n < SQLStringList.Count; n++)
{
string strsql = SQLStringList[n].ToString();
if (strsql.Trim().Length > 1)
{
cmd.CommandText = strsql;
cmd.ExecuteNonQuery();
}
}
tx.Commit();
}
catch (System.Data.OleDb.OleDbException E)
{
tx.Rollback();
throw new Exception(E.Message);
}
}
}
///
/// 执行带一个存储过程参数的的SQL语句。
///
/// SQL语句
/// 参数内容,比如一个字段是格式复杂的文章,有特殊符号,可以通过这个方式添加
/// 影响的记录数
public static int ExecuteSql(string SQLString, string content)
{
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
OleDbCommand cmd = new OleDbCommand(SQLString, connection);
System.Data.OleDb.OleDbParameter myParameter = new System.Data.OleDb.OleDbParameter("@content", OleDbType.VarChar);
myParameter.Value = content;
cmd.Parameters.Add(myParameter);
try
{
connection.Open();
int rows = cmd.ExecuteNonQuery();
return rows;
}
catch (System.Data.OleDb.OleDbException E)
{
throw new Exception(E.Message);
}
finally
{
cmd.Dispose();
connection.Close();
}
}
}
///
/// 向数据库里插入图像格式的字段(和上面情况类似的另一种实例)
///
/// SQL语句
/// 图像字节,数据库的字段类型为image的情况
/// 影响的记录数
public static int ExecuteSqlInsertImg(string strSQL, byte[] fs)
{
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
OleDbCommand cmd = new OleDbCommand(strSQL, connection);
System.Data.OleDb.OleDbParameter myParameter = new System.Data.OleDb.OleDbParameter("@fs", OleDbType.Binary);
myParameter.Value = fs;
cmd.Parameters.Add(myParameter);
try
{
connection.Open();
int rows = cmd.ExecuteNonQuery();
return rows;
}
catch (System.Data.OleDb.OleDbException E)
{
throw new Exception(E.Message);
}
finally
{
cmd.Dispose();
connection.Close();
}
}
}
///
/// 执行一条计算查询结果语句,返回查询结果(object)。
///
/// 计算查询结果语句
/// 查询结果(object)
public static object GetSingle(string SQLString)
{
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
using (OleDbCommand cmd = new OleDbCommand(SQLString, connection))
{
try
{
connection.Open();
object obj = cmd.ExecuteScalar();
if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
{
return null;
}
else
{
return obj;
}
}
catch (System.Data.OleDb.OleDbException e)
{
connection.Close();
throw new Exception(e.Message);
}
}
}
}
///
/// 执行查询语句,返回OleDbDataReader
///
/// 查询语句
/// OleDbDataReader
public static OleDbDataReader ExecuteReader(string strSQL)
{
OleDbConnection connection = new OleDbConnection(connectionString);
OleDbCommand cmd = new OleDbCommand(strSQL, connection);
try
{
connection.Open();
OleDbDataReader myReader = cmd.ExecuteReader();
return myReader;
}
catch (System.Data.OleDb.OleDbException e)
{
throw new Exception(e.Message);
}
}
///
/// 执行查询语句,返回DataSet
///
/// 查询语句
/// DataSet
public static DataSet Query(string SQLString)
{
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
DataSet ds = new DataSet();
try
{
connection.Open();
OleDbDataAdapter command = new OleDbDataAdapter(SQLString, connection);
command.Fill(ds, "ds");
}
catch (System.Data.OleDb.OleDbException ex)
{
throw new Exception(ex.Message);
}
return ds;
}
}
#endregion
#region 执行带参数的SQL语句
///
/// 执行SQL语句,返回影响的记录数
///
/// SQL语句
/// 影响的记录数
public static int ExecuteSql(string SQLString, params OleDbParameter[] cmdParms)
{
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
using (OleDbCommand cmd = new OleDbCommand())
{
try
{
PrepareCommand(cmd, connection, null, SQLString, cmdParms);
int rows = cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
return rows;
}
catch (System.Data.OleDb.OleDbException E)
{
throw new Exception(E.Message);
}
}
}
}
///
/// 执行多条SQL语句,实现数据库事务。
///
/// SQL语句的哈希表(key为sql语句,value是该语句的OleDbParameter[])
public static void ExecuteSqlTran(Hashtable SQLStringList)
{
using (OleDbConnection conn = new OleDbConnection(connectionString))
{
conn.Open();
using (OleDbTransaction trans = conn.BeginTransaction())
{
OleDbCommand cmd = new OleDbCommand();
try
{
//循环
foreach (DictionaryEntry myDE in SQLStringList)
{
string cmdText = myDE.Key.ToString();
OleDbParameter[] cmdParms = (OleDbParameter[])myDE.Value;
PrepareCommand(cmd, conn, trans, cmdText, cmdParms);
int val = cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
trans.Commit();
}
}
catch
{
trans.Rollback();
throw;
}
}
}
}
///
/// 执行一条计算查询结果语句,返回查询结果(object)。
///
/// 计算查询结果语句
/// 查询结果(object)
public static object GetSingle(string SQLString, params OleDbParameter[] cmdParms)
{
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
using (OleDbCommand cmd = new OleDbCommand())
{
try
{
PrepareCommand(cmd, connection, null, SQLString, cmdParms);
object obj = cmd.ExecuteScalar();
cmd.Parameters.Clear();
if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
{
return null;
}
else
{
return obj;
}
}
catch (System.Data.OleDb.OleDbException e)
{
throw new Exception(e.Message);
}
}
}
}
///
/// 执行查询语句,返回OleDbDataReader
///
/// 查询语句
/// OleDbDataReader
public static OleDbDataReader ExecuteReader(string SQLString, params OleDbParameter[] cmdParms)
{
OleDbConnection connection = new OleDbConnection(connectionString);
OleDbCommand cmd = new OleDbCommand();
try
{
PrepareCommand(cmd, connection, null, SQLString, cmdParms);
OleDbDataReader myReader = cmd.ExecuteReader();
cmd.Parameters.Clear();
return myReader;
}
catch (System.Data.OleDb.OleDbException e)
{
throw new Exception(e.Message);
}
}
///
/// 执行查询语句,返回DataSet
///
/// 查询语句
/// DataSet
public static DataSet Query(string SQLString, params OleDbParameter[] cmdParms)
{
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
OleDbCommand cmd = new OleDbCommand();
PrepareCommand(cmd, connection, null, SQLString, cmdParms);
using (OleDbDataAdapter da = new OleDbDataAdapter(cmd))
{
DataSet ds = new DataSet();
try
{
da.Fill(ds, "ds");
cmd.Parameters.Clear();
}
catch (System.Data.OleDb.OleDbException ex)
{
throw new Exception(ex.Message);
}
return ds;
}
}
}
private static void PrepareCommand(OleDbCommand cmd, OleDbConnection conn, OleDbTransaction trans, string cmdText, OleDbParameter[] cmdParms)
{
if (conn.State != ConnectionState.Open)
conn.Open();
cmd.Connection = conn;
cmd.CommandText = cmdText;
if (trans != null)
cmd.Transaction = trans;
cmd.CommandType = CommandType.Text;//cmdType;
if (cmdParms != null)
{
foreach (OleDbParameter parm in cmdParms)
cmd.Parameters.Add(parm);
}
}
#endregion
}
}
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
using System.Data.Common;
using System.Data;
using System.Text.RegularExpressions;
namespace Core.DBUtility
{
///
/// 查询条件组合辅助类
///
public class SearchCondition
{
#region 添加查询条件
private Hashtable conditionTable = new Hashtable();
///
/// 查询条件列表
///
public Hashtable ConditionTable
{
get { return this.conditionTable; }
}
///
/// 为查询添加条件
///
/// 用法一:
/// SearchCondition searchObj = new SearchCondition();
/// searchObj.AddCondition("Test", 1, SqlOperator.NotEqual);
/// searchObj.AddCondition("Test2", "Test2Value", SqlOperator.Like);
/// string conditionSql = searchObj.BuildConditionSql();
///
/// 用法二:AddCondition函数可以串起来添加多个条件
/// SearchCondition searchObj = new SearchCondition();
/// searchObj.AddCondition("Test", 1, SqlOperator.NotEqual).AddCondition("Test2", "Test2Value", SqlOperator.Like);
/// string conditionSql = searchObj.BuildConditionSql();
///
///
/// 字段名称
/// 字段值
/// SqlOperator枚举类型
/// 增加条件后的Hashtable
public SearchCondition AddCondition(string fielName, object fieldValue, SqlOperator sqlOperator)
{
this.conditionTable.Add(System.Guid.NewGuid()/*fielName*/, new SearchInfo(fielName, fieldValue, sqlOperator));
return this;
}
///
/// 为查询添加条件
///
/// 用法一:
/// SearchCondition searchObj = new SearchCondition();
/// searchObj.AddCondition("Test", 1, SqlOperator.NotEqual, false);
/// searchObj.AddCondition("Test2", "Test2Value", SqlOperator.Like, true);
/// string conditionSql = searchObj.BuildConditionSql();
///
/// 用法二:AddCondition函数可以串起来添加多个条件
/// SearchCondition searchObj = new SearchCondition();
/// searchObj.AddCondition("Test", 1, SqlOperator.NotEqual, false).AddCondition("Test2", "Test2Value", SqlOperator.Like, true);
/// string conditionSql = searchObj.BuildConditionSql();
///
///
/// 字段名称
/// 字段值
/// SqlOperator枚举类型
/// 如果字段为空或者Null则不作为查询条件
///
public SearchCondition AddCondition(string fielName, object fieldValue, SqlOperator sqlOperator, bool excludeIfEmpty)
{
this.conditionTable.Add(System.Guid.NewGuid()/*fielName*/, new SearchInfo(fielName, fieldValue, sqlOperator, excludeIfEmpty));
return this;
}
///
/// 将多个条件分组归类作为一个条件来查询,
/// 如需构造一个括号内的条件 ( Test = "AA1" OR Test = "AA2")
///
/// 字段名称
/// 字段值
/// SqlOperator枚举类型
/// 如果字段为空或者Null则不作为查询条件
/// 分组的名称,如需构造一个括号内的条件 ( Test = "AA1" OR Test = "AA2"), 定义一个组名集中条件
///
public SearchCondition AddCondition(string fielName, object fieldValue, SqlOperator sqlOperator,
bool excludeIfEmpty, string groupName)
{
this.conditionTable.Add(System.Guid.NewGuid()/*fielName*/, new SearchInfo(fielName, fieldValue, sqlOperator, excludeIfEmpty, groupName));
return this;
}
#endregion
///
/// 根据对象构造相关的条件语句(不使用参数),如返回的语句是:
/// = 'Value6' AND Test7 <= 'value7' AND Test <> '1' AND Test5 > 'Value5' AND Test2 Like '%Value2%' AND Test3 = 'Value3'
/// ]]>
///
///
public string BuildConditionSql(DatabaseType dbType)
{
string sql = " Where (1=1) ";
string fieldName = string.Empty;
SearchInfo searchInfo = null;
StringBuilder sb = new StringBuilder();
sql += BuildGroupCondiction(dbType);
foreach (DictionaryEntry de in this.conditionTable)
{
searchInfo = (SearchInfo)de.Value;
TypeCode typeCode = Type.GetTypeCode(searchInfo.FieldValue.GetType());
//如果选择ExcludeIfEmpty为True,并且该字段为空值的话,跳过
if (searchInfo.ExcludeIfEmpty &&
(searchInfo.FieldValue == null || string.IsNullOrEmpty(searchInfo.FieldValue.ToString())))
{
continue;
}
//只有组别名称为空才继续,即正常的sql条件
if (string.IsNullOrEmpty(searchInfo.GroupName))
{
if (searchInfo.SqlOperator == SqlOperator.Like)
{
sb.AppendFormat(" AND {0} {1} '{2}'", searchInfo.FieldName,
this.ConvertSqlOperator(searchInfo.SqlOperator), string.Format("%{0}%", searchInfo.FieldValue));
}
else if (searchInfo.SqlOperator == SqlOperator.NotLike)
{
sb.AppendFormat(" AND {0} {1} '{2}'", searchInfo.FieldName,
this.ConvertSqlOperator(searchInfo.SqlOperator), string.Format("%{0}%", searchInfo.FieldValue));
}
else if (searchInfo.SqlOperator == SqlOperator.LikeStartAt)
{
sb.AppendFormat(" AND {0} {1} '{2}'", searchInfo.FieldName,
this.ConvertSqlOperator(searchInfo.SqlOperator), string.Format("{0}%", searchInfo.FieldValue));
}
else if (searchInfo.SqlOperator == SqlOperator.In)
{
sb.AppendFormat(" AND {0} {1} {2}", searchInfo.FieldName,
this.ConvertSqlOperator(searchInfo.SqlOperator), string.Format("({0})", searchInfo.FieldValue));
}
else
{
if (dbType == DatabaseType.Oracle)
{
#region 特殊Oracle操作
if (IsDate(searchInfo.FieldValue.ToString()))
{
sb.AppendFormat(" AND {0} {1} to_date('{2}','YYYY-MM-dd')", searchInfo.FieldName,
this.ConvertSqlOperator(searchInfo.SqlOperator), searchInfo.FieldValue);
}
else if (IsDateHourMinute(searchInfo.FieldValue.ToString()))
{
sb.AppendFormat(" AND {0} {1} to_date('{2}','YYYY-MM-dd HH:mi')", searchInfo.FieldName,
this.ConvertSqlOperator(searchInfo.SqlOperator), searchInfo.FieldValue);
}
else if (!searchInfo.ExcludeIfEmpty)
{
//如果要进行空值查询的时候
if (searchInfo.SqlOperator == SqlOperator.Equal)
{
sb.AppendFormat(" AND ({0} is null or {0}='')", searchInfo.FieldName);
}
else if (searchInfo.SqlOperator == SqlOperator.NotEqual)
{
sb.AppendFormat(" AND {0} is not null", searchInfo.FieldName);
}
}
else
{
sb.AppendFormat(" AND {0} {1} '{2}'", searchInfo.FieldName,
this.ConvertSqlOperator(searchInfo.SqlOperator), searchInfo.FieldValue);
}
#endregion
}
else if (dbType == DatabaseType.Access)
{
#region 特殊Access操作
if (searchInfo.SqlOperator == SqlOperator.Equal &&
typeCode == TypeCode.String && string.IsNullOrEmpty(searchInfo.FieldValue.ToString()))
{
sb.AppendFormat(" AND ({0} {1} '{2}' OR {0} IS NULL)", searchInfo.FieldName,
this.ConvertSqlOperator(searchInfo.SqlOperator), searchInfo.FieldValue);
}
else
{
if (typeCode == TypeCode.DateTime)
{
sb.AppendFormat(" AND {0} {1} #{2}#", searchInfo.FieldName,
this.ConvertSqlOperator(searchInfo.SqlOperator), searchInfo.FieldValue);
}
else if (typeCode == TypeCode.Byte || typeCode == TypeCode.Decimal || typeCode == TypeCode.Double ||
typeCode == TypeCode.Int16 || typeCode == TypeCode.Int32 || typeCode == TypeCode.Int64 ||
typeCode == TypeCode.SByte || typeCode == TypeCode.Single || typeCode == TypeCode.UInt16 ||
typeCode == TypeCode.UInt32 || typeCode == TypeCode.UInt64)
{
//数值类型操作
sb.AppendFormat(" AND {0} {1} {2}", searchInfo.FieldName,
this.ConvertSqlOperator(searchInfo.SqlOperator), searchInfo.FieldValue);
}
else
{
sb.AppendFormat(" AND {0} {1} '{2}'", searchInfo.FieldName,
this.ConvertSqlOperator(searchInfo.SqlOperator), searchInfo.FieldValue);
}
}
#endregion
}
else //if (dbType == DatabaseType.SqlServer)
{
sb.AppendFormat(" AND {0} {1} '{2}'", searchInfo.FieldName,
this.ConvertSqlOperator(searchInfo.SqlOperator), searchInfo.FieldValue);
}
}
}
}
sql += sb.ToString();
return sql;
}
///
/// 建立分组条件
///
///
private string BuildGroupCondiction(DatabaseType dbType)
{
Hashtable ht = GetGroupNames();
SearchInfo searchInfo = null;
StringBuilder sb = new StringBuilder();
string sql = string.Empty;
string tempSql = string.Empty;
foreach (string groupName in ht.Keys)
{
sb = new StringBuilder();
tempSql = " AND ({0})";
foreach (DictionaryEntry de in this.conditionTable)
{
searchInfo = (SearchInfo)de.Value;
TypeCode typeCode = Type.GetTypeCode(searchInfo.FieldValue.GetType());
//如果选择ExcludeIfEmpty为True,并且该字段为空值的话,跳过
if (searchInfo.ExcludeIfEmpty &&
(searchInfo.FieldValue == null || string.IsNullOrEmpty(searchInfo.FieldValue.ToString())) )
{
continue;
}
if (groupName.Equals(searchInfo.GroupName, StringComparison.OrdinalIgnoreCase))
{
if (searchInfo.SqlOperator == SqlOperator.Like)
{
sb.AppendFormat(" OR {0} {1} '{2}'", searchInfo.FieldName,
this.ConvertSqlOperator(searchInfo.SqlOperator), string.Format("%{0}%", searchInfo.FieldValue));
}
else if (searchInfo.SqlOperator == SqlOperator.NotLike)
{
sb.AppendFormat(" OR {0} {1} '{2}'", searchInfo.FieldName,
this.ConvertSqlOperator(searchInfo.SqlOperator), string.Format("%{0}%", searchInfo.FieldValue));
}
else if (searchInfo.SqlOperator == SqlOperator.LikeStartAt)
{
sb.AppendFormat(" OR {0} {1} '{2}'", searchInfo.FieldName,
this.ConvertSqlOperator(searchInfo.SqlOperator), string.Format("{0}%", searchInfo.FieldValue));
}
else
{
if (dbType == DatabaseType.Oracle)
{
#region Oracle分组
if (IsDate(searchInfo.FieldValue.ToString()))
{
sb.AppendFormat(" OR {0} {1} to_date('{2}','YYYY-MM-dd')", searchInfo.FieldName,
this.ConvertSqlOperator(searchInfo.SqlOperator), searchInfo.FieldValue);
}
else if (IsDateHourMinute(searchInfo.FieldValue.ToString()))
{
sb.AppendFormat(" OR {0} {1} to_date('{2}','YYYY-MM-dd HH:mi')", searchInfo.FieldName,
this.ConvertSqlOperator(searchInfo.SqlOperator), searchInfo.FieldValue);
}
else if (!searchInfo.ExcludeIfEmpty)
{
//如果要进行空值查询的时候
if (searchInfo.SqlOperator == SqlOperator.Equal)
{
sb.AppendFormat(" OR ({0} is null or {0}='')", searchInfo.FieldName);
}
else if (searchInfo.SqlOperator == SqlOperator.NotEqual)
{
sb.AppendFormat(" OR {0} is not null", searchInfo.FieldName);
}
}
else
{
sb.AppendFormat(" OR {0} {1} '{2}'", searchInfo.FieldName,
this.ConvertSqlOperator(searchInfo.SqlOperator), searchInfo.FieldValue);
}
#endregion
}
else if (dbType == DatabaseType.Access)
{
#region Access分组
if (typeCode == TypeCode.DateTime)
{
sb.AppendFormat(" OR {0} {1} #{2}#", searchInfo.FieldName,
this.ConvertSqlOperator(searchInfo.SqlOperator), searchInfo.FieldValue);
}
else if (typeCode == TypeCode.Byte || typeCode == TypeCode.Decimal || typeCode == TypeCode.Double ||
typeCode == TypeCode.Int16 || typeCode == TypeCode.Int32 || typeCode == TypeCode.Int64 ||
typeCode == TypeCode.SByte || typeCode == TypeCode.Single || typeCode == TypeCode.UInt16 ||
typeCode == TypeCode.UInt32 || typeCode == TypeCode.UInt64)
{
//数值类型操作
sb.AppendFormat(" OR {0} {1} {2}", searchInfo.FieldName,
this.ConvertSqlOperator(searchInfo.SqlOperator), searchInfo.FieldValue);
}
else
{
sb.AppendFormat(" OR {0} {1} '{2}'", searchInfo.FieldName,
this.ConvertSqlOperator(searchInfo.SqlOperator), searchInfo.FieldValue);
}
#endregion
}
else //if (dbType == DatabaseType.SqlServer)
{
#region SqlServer分组
if (searchInfo.SqlOperator == SqlOperator.Like)
{
sb.AppendFormat(" OR {0} {1} '{2}'", searchInfo.FieldName,
this.ConvertSqlOperator(searchInfo.SqlOperator), string.Format("%{0}%", searchInfo.FieldValue));
}
else
{
sb.AppendFormat(" OR {0} {1} '{2}'", searchInfo.FieldName,
this.ConvertSqlOperator(searchInfo.SqlOperator), searchInfo.FieldValue);
}
#endregion
}
}
}
}
if(!string.IsNullOrEmpty(sb.ToString()))
{
tempSql = string.Format(tempSql, sb.ToString().Substring(3));//从第一个Or开始位置
sql += tempSql;
}
}
return sql;
}
///
/// 获取给定条件集合的组别对象集合
///
///
private Hashtable GetGroupNames()
{
Hashtable htGroupNames = new Hashtable();
SearchInfo searchInfo = null;
foreach (DictionaryEntry de in this.conditionTable)
{
searchInfo = (SearchInfo)de.Value;
if (!string.IsNullOrEmpty(searchInfo.GroupName) && !htGroupNames.Contains(searchInfo.GroupName))
{
htGroupNames.Add(searchInfo.GroupName, searchInfo.GroupName);
}
}
return htGroupNames;
}
/////
///// 创建用于Enterprise Library的DbCommand对象。
///// 该对象包含了可以运行的参数化语句和参数列表。
/////
///// 函数用法如下:
/////
/////
///// Database db = DatabaseFactory.CreateDatabase();
///// SearchCondition searchObj = new SearchCondition();
///// searchObj.AddCondition("Name", "测试" , SqlOperator.Like)
///// .AddCondition("ID", 1, SqlOperator.MoreThanOrEqual);
///// DbCommand dbComand = searchObj.BuildDbCommand(db, "select Comments from Test", " Order by Name");
///// using (IDataReader dr = db.ExecuteReader(dbComand))
///// {
///// while (dr.Read())
///// {
///// this.txtSql.Text += "\r\n" + dr["Comments"].ToString();
///// }
///// }
/////
/////
/////
/////
///// Enterprise Library的DbCommand对象
///// Database对象
///// 除了Where条件和排序语句的主Sql语句
///// 排序语句
///// Enterprise Library的DbCommand对象
//public DbCommand BuildDbCommand(Database db, string mainSql, string orderSql)
//{
// string sql = " Where (1=1) ";
// string fieldName = string.Empty;
// SearchInfo searchInfo = null;
// StringBuilder sb = new StringBuilder();
// foreach (DictionaryEntry de in this.ConditionTable)
// {
// searchInfo = (SearchInfo)de.Value;
// //如果选择ExcludeIfEmpty为True,并且该字段为空值的话,跳过
// if (searchInfo.ExcludeIfEmpty &&
// (searchInfo.FieldValue == null || string.IsNullOrEmpty(searchInfo.FieldValue.ToString())))
// {
// continue;
// }
// sb.AppendFormat(" AND {0} {1} @{0} ", searchInfo.FieldName, this.ConvertSqlOperator(searchInfo.SqlOperator));
// }
// sql += sb.ToString();
// sql = mainSql + sql + orderSql;
// DbCommand dbCommand = db.GetSqlStringCommand(sql);
// foreach (DictionaryEntry de in this.ConditionTable)
// {
// searchInfo = (SearchInfo)de.Value;
// //如果选择ExcludeIfEmpty为True,并且该字段为空值的话,跳过
// if (searchInfo.ExcludeIfEmpty && string.IsNullOrEmpty((string)searchInfo.FieldValue))
// {
// continue;
// }
// if (searchInfo.SqlOperator == SqlOperator.Like)
// {
// if ( !string.IsNullOrEmpty(searchInfo.FieldValue.ToString()) )
// db.AddInParameter(dbCommand, searchInfo.FieldName,
// this.GetFieldDbType(searchInfo.FieldValue), string.Format("%{0}%", searchInfo.FieldValue));
// }
// else
// {
// db.AddInParameter(dbCommand, searchInfo.FieldName,
// this.GetFieldDbType(searchInfo.FieldValue), searchInfo.FieldValue);
// }
// }
// return dbCommand;
//}
#region 辅助函数
///
/// 转换枚举类型为对应的Sql语句操作符号
///
/// SqlOperator枚举对象
/// " "<>" ">=")]]>
private string ConvertSqlOperator(SqlOperator sqlOperator)
{
string stringOperator = " = ";
switch (sqlOperator)
{
case SqlOperator.Equal:
stringOperator = " = ";
break;
case SqlOperator.LessThan:
stringOperator = " < ";
break;
case SqlOperator.LessThanOrEqual:
stringOperator = " <= ";
break;
case SqlOperator.Like:
stringOperator = " Like ";
break;
case SqlOperator.NotLike:
stringOperator = " NOT Like ";
break;
case SqlOperator.LikeStartAt:
stringOperator = " Like ";
break;
case SqlOperator.MoreThan:
stringOperator = " > ";
break;
case SqlOperator.MoreThanOrEqual:
stringOperator = " >= ";
break;
case SqlOperator.NotEqual:
stringOperator = " <> ";
break;
case SqlOperator.In:
stringOperator = " in ";
break;
default:
break;
}
return stringOperator;
}
///
/// 根据传入对象的值类型获取其对应的DbType类型
///
/// 对象的值
/// DbType类型
private DbType GetFieldDbType(object fieldValue)
{
DbType type = DbType.String;
switch (fieldValue.GetType().ToString())
{
case "System.Int16":
type = DbType.Int16;
break;
case "System.UInt16":
type = DbType.UInt16;
break;
case "System.Single":
type = DbType.Single;
break;
case "System.UInt32":
type = DbType.UInt32;
break;
case "System.Int32":
type = DbType.Int32;
break;
case "System.UInt64":
type = DbType.UInt64;
break;
case "System.Int64":
type = DbType.Int64;
break;
case "System.String":
type = DbType.String;
break;
case "System.Double":
type = DbType.Double;
break;
case "System.Decimal":
type = DbType.Decimal;
break;
case "System.Byte":
type = DbType.Byte;
break;
case "System.Boolean":
type = DbType.Boolean;
break;
case "System.DateTime":
type = DbType.DateTime;
break;
case "System.Guid":
type = DbType.Guid;
break;
default:
break;
}
return type;
}
///
/// 判断输入的字符是否为日期
///
///
///
internal bool IsDate(string strValue)
{
return Regex.IsMatch(strValue, @"^((\d{2}(([02468][048])|([13579][26]))[\-\/\s]?((((0?[13578])|(1[02]))[\-\/\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\-\/\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\-\/\s]?((0?[1-9])|([1-2][0-9])))))|(\d{2}(([02468][1235679])|([13579][01345789]))[\-\/\s]?((((0?[13578])|(1[02]))[\-\/\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\-\/\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\-\/\s]?((0?[1-9])|(1[0-9])|(2[0-8]))))))");
}
///
/// 判断输入的字符是否为日期,如2004-07-12 14:25|||1900-01-01 00:00|||9999-12-31 23:59
///
///
///
internal bool IsDateHourMinute(string strValue)
{
return Regex.IsMatch(strValue, @"^(19[0-9]{2}|[2-9][0-9]{3})-((0(1|3|5|7|8)|10|12)-(0[1-9]|1[0-9]|2[0-9]|3[0-1])|(0(4|6|9)|11)-(0[1-9]|1[0-9]|2[0-9]|30)|(02)-(0[1-9]|1[0-9]|2[0-9]))\x20(0[0-9]|1[0-9]|2[0-3])(:[0-5][0-9]){1}$");
}
#endregion
}
}
using System;
using System.IO.Compression;
using System.Text;
using System.Net;
using System.IO;
using System.Threading;
using System.Text.RegularExpressions;
using System.Web;
namespace Core.Html
{
///
///1、获取HTML
///1.1获取指定页面的HTML代码 GetHtml(string url, string postData, bool isPost, CookieContainer cookieContainer)
///1.2获取HTMLGetHtml(string url, CookieContainer cookieContainer)
///2、获取字符流
///2.1获取字符流GetStream(string url, CookieContainer cookieContainer)
///3、清除HTML标记
///3.1清除HTML标记 NoHTML(string Htmlstring)
///4、匹配页面的链接
///4.1获取页面的链接正则 GetHref(string HtmlCode)
///5、匹配页面的图片地址
/// 5.1匹配页面的图片地址 GetImgSrc(string HtmlCode, string imgHttp)
///5.2匹配中的图片路径实际链接 GetImg(string ImgString, string imgHttp)
///6、抓取远程页面内容
/// 6.1以GET方式抓取远程页面内容 Get_Http(string tUrl)
/// 6.2以POST方式抓取远程页面内容 Post_Http(string url, string postData, string encodeType)
///7、压缩HTML输出
///7.1压缩HTML输出 ZipHtml(string Html)
///8、过滤HTML标签
/// 8.1过滤指定HTML标签 DelHtml(string s_TextStr, string html_Str)
/// 8.2过滤HTML中的不安全标签 RemoveUnsafeHtml(string content)
/// HTML转行成TEXT HtmlToTxt(string strHtml)
/// 字符串转换为 HtmlStringToHtml(string str)
/// html转换成字符串HtmlToString(string strHtml)
/// 获取URL编码
/// 判断URL是否有效
/// 返回 HTML 字符串的编码解码结果
///
public class HtmlHelper
{
#region 私有字段
private static CookieContainer cc = new CookieContainer();
private static string contentType = "application/x-www-form-urlencoded";
private static string accept = "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg," +
" application/x-shockwave-flash, application/x-silverlight, " +
"application/vnd.ms-excel, application/vnd.ms-powerpoint, " +
"application/msword, application/x-ms-application," +
" application/x-ms-xbap," +
" application/vnd.ms-xpsdocument, application/xaml+xml, application/x-silverlight-2-b1, */*";
private static string userAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1;" +
" .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022)";
private static Encoding encoding = Encoding.GetEncoding("utf-8");
private static int delay = 1000;
private static int maxTry = 300;
private static int currentTry = 0;
#endregion
#region 公有属性
///
/// Cookie容器
///
public static CookieContainer CookieContainer
{
get
{
return cc;
}
}
///
/// 获取网页源码时使用的编码
///
public static Encoding Encoding
{
get
{
return encoding;
}
set
{
encoding = value;
}
}
public static int NetworkDelay
{
get
{
Random r = new Random();
return (r.Next(delay, delay * 2));
// return (r.Next(delay / 1000, delay / 1000 * 2)) * 1000;
}
set
{
delay = value;
}
}
public static int MaxTry
{
get
{
return maxTry;
}
set
{
maxTry = value;
}
}
#endregion
#region 1、获取HTML
///
/// 1.1获取指定页面的HTML代码
///
/// 指定页面的路径
/// post 提交的字符串
/// 是否以post方式发送请求
/// Cookie集合
public static string GetHtml(string url, string postData, bool isPost, CookieContainer cookieContainer)
{
if (string.IsNullOrEmpty(postData))
{
return GetHtml(url, cookieContainer);
}
Thread.Sleep(NetworkDelay);
currentTry++;
HttpWebRequest httpWebRequest = null;
HttpWebResponse httpWebResponse = null;
try
{
byte[] byteRequest = Encoding.Default.GetBytes(postData);
httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(url);
httpWebRequest.CookieContainer = cookieContainer;
httpWebRequest.ContentType = contentType;
httpWebRequest.ServicePoint.ConnectionLimit = maxTry;
httpWebRequest.Referer = url;
httpWebRequest.Accept = accept;
httpWebRequest.UserAgent = userAgent;
httpWebRequest.Method = isPost ? "POST" : "GET";
httpWebRequest.ContentLength = byteRequest.Length;
httpWebRequest.AllowAutoRedirect = false;
Stream stream = httpWebRequest.GetRequestStream();
stream.Write(byteRequest, 0, byteRequest.Length);
stream.Close();
try
{
httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
//redirectURL = httpWebResponse.Headers["Location"];// Get redirected uri
}
catch (WebException ex)
{
httpWebResponse = (HttpWebResponse)ex.Response;
}
//httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
Stream responseStream = httpWebResponse.GetResponseStream();
StreamReader streamReader = new StreamReader(responseStream, encoding);
string html = streamReader.ReadToEnd();
streamReader.Close();
responseStream.Close();
currentTry = 0;
httpWebRequest.Abort();
httpWebResponse.Close();
return html;
}
catch (Exception e)
{
if (currentTry <= maxTry)
{
GetHtml(url, postData, isPost, cookieContainer);
}
currentTry--;
if (httpWebRequest != null) httpWebRequest.Abort();
if (httpWebResponse != null) httpWebResponse.Close();
return string.Empty;
}
}
///
/// 1.2获取HTML
///
/// 地址
/// Cookie集合
public static string GetHtml(string url, CookieContainer cookieContainer)
{
Thread.Sleep(NetworkDelay);
currentTry++;
HttpWebRequest httpWebRequest = null;
HttpWebResponse httpWebResponse = null;
try
{
httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(url);
httpWebRequest.CookieContainer = cookieContainer;
httpWebRequest.ContentType = contentType;
httpWebRequest.ServicePoint.ConnectionLimit = maxTry;
httpWebRequest.Referer = url;
httpWebRequest.Accept = accept;
httpWebRequest.UserAgent = userAgent;
httpWebRequest.Method = "GET";
httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
Stream responseStream = httpWebResponse.GetResponseStream();
StreamReader streamReader = new StreamReader(responseStream, encoding);
string html = streamReader.ReadToEnd();
streamReader.Close();
responseStream.Close();
currentTry--;
httpWebRequest.Abort();
httpWebResponse.Close();
return html;
}
catch (Exception e)
{
if (currentTry <= maxTry) GetHtml(url, cookieContainer);
currentTry--;
if (httpWebRequest != null) httpWebRequest.Abort();
if (httpWebResponse != null) httpWebResponse.Close();
return string.Empty;
}
}
#endregion
#region 2、获取字符流
///
/// 2.1获取字符流
///
//---------------------------------------------------------------------------------------------------------------
// 示例:
// System.Net.CookieContainer cookie = new System.Net.CookieContainer();
// Stream s = HttpHelper.GetStream("http://ptlogin2.qq.com/getimage?aid=15000102&0.43878429697395826", cookie);
// picVerify.Image = Image.FromStream(s);
//---------------------------------------------------------------------------------------------------------------
/// 地址
/// cookieContainer
public static Stream GetStream(string url, CookieContainer cookieContainer)
{
currentTry++;
HttpWebRequest httpWebRequest = null;
HttpWebResponse httpWebResponse = null;
try
{
httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(url);
httpWebRequest.CookieContainer = cookieContainer;
httpWebRequest.ContentType = contentType;
httpWebRequest.ServicePoint.ConnectionLimit = maxTry;
httpWebRequest.Referer = url;
httpWebRequest.Accept = accept;
httpWebRequest.UserAgent = userAgent;
httpWebRequest.Method = "GET";
httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
Stream responseStream = httpWebResponse.GetResponseStream();
currentTry--;
return responseStream;
}
catch (Exception e)
{
if (currentTry <= maxTry)
{
GetHtml(url, cookieContainer);
}
currentTry--;
if (httpWebRequest != null)
{
httpWebRequest.Abort();
} if (httpWebResponse != null)
{
httpWebResponse.Close();
}
return null;
}
}
#endregion
#region 3、清除HTML标记
///
///3.1清除HTML标记
///
///包括HTML的源码
///已经去除后的文字
public static string RemoveHTML(string Htmlstring)
{
//删除脚本
Htmlstring = Regex.Replace(Htmlstring, @"", "", RegexOptions.IgnoreCase);
//删除HTML
Regex regex = new Regex("<.+?>", RegexOptions.IgnoreCase);
Htmlstring = regex.Replace(Htmlstring, "");
Htmlstring = Regex.Replace(Htmlstring, @"<(.[^>]*)>", "", RegexOptions.IgnoreCase);
Htmlstring = Regex.Replace(Htmlstring, @"([\r\n])[\s]+", "", RegexOptions.IgnoreCase);
Htmlstring = Regex.Replace(Htmlstring, @"-->", "", RegexOptions.IgnoreCase);
Htmlstring = Regex.Replace(Htmlstring, @"",
@"");
return content;
}
charset = m.Result("${charset}");
}
}
else
{
response.Close();
charset = sCoding.ToLower();
}
try
{
content = System.Text.Encoding.GetEncoding(charset).GetString(buffer);
}
catch (ArgumentException)
{//指定的编码不可识别
content = System.Text.Encoding.GetEncoding("gb2312").GetString(buffer);
}
//content = CText.RemoveByReg(content, @"");
}
catch
{
content = "";
}
return content;
}
private static HttpWebResponse _MyGetResponse(string sUrl)
{
int iTimeOut = 10000;
//try
//{
// //iTimeOut = int.Parse(System.Configuration.ConfigurationManager.AppSettings["SocketTimeOut"]);
//}
//catch { iTimeOut = 10000; }
bool bCookie = false;
bool bRepeat = false;
Uri target = new Uri(sUrl);
ReCatch:
try
{
HttpWebRequest resquest = (HttpWebRequest)WebRequest.Create(target);
resquest.MaximumResponseHeadersLength = -1;
resquest.ReadWriteTimeout = 120000;//120秒就超时
resquest.Timeout = iTimeOut;
resquest.MaximumAutomaticRedirections = 50;
resquest.MaximumResponseHeadersLength = 5;
resquest.AllowAutoRedirect = true;
if (bCookie)
{
resquest.CookieContainer = new CookieContainer();
}
resquest.UserAgent = "Mozilla/6.0 (compatible; MSIE 6.0; Windows NT 5.1)";
//resquest.UserAgent = @"Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.2; .NET CLR 1.1.4322; .NET CLR 2.0.50727; InfoPath.1) Web-Sniffer/1.0.24";
//resquest.KeepAlive = true;
return (HttpWebResponse)resquest.GetResponse();
}
catch (WebException we)
{
if (!bRepeat)
{
bRepeat = true;
bCookie = true;
goto ReCatch;
}
return null;
}
catch
{
return null;
}
}
private static byte[] GetContent(Stream stream)
{
ArrayList arBuffer = new ArrayList();
const int BUFFSIZE = 4096;
try
{
byte[] buffer = new byte[BUFFSIZE];
int count = stream.Read(buffer, 0, BUFFSIZE);
while (count > 0)
{
for (int i = 0; i < count; i++)
{
arBuffer.Add(buffer[i]);
}
count = stream.Read(buffer, 0, BUFFSIZE);
}
}
catch { }
return (byte[])arBuffer.ToArray(System.Type.GetType("System.Byte"));
}
public static string GetHttpHead(string sUrl)
{
string sHead = "";
Uri uri = new Uri(sUrl);
try
{
WebRequest req = WebRequest.Create(uri);
WebResponse resp = req.GetResponse();
WebHeaderCollection headers = resp.Headers;
string[] sKeys = headers.AllKeys;
foreach (string sKey in sKeys)
{
sHead += sKey + ":" + headers[sKey] + "\r\n";
}
}
catch
{
}
return sHead;
}
///
/// 处理框架页面问题。如果该页面是框架结构的话,返回该框架
///
///
///
public static string[] DealWithFrame(string url, string content)
{
string regFrame = @"]*src\s*=\s*(?:""(?[^""]+)""|'(?[^']+)'|(?[^\s>""']+))[^>]*>";
return DealWithFrame(regFrame, url, content);
}
///
/// 处理浮动桢问题。如果该页面存在浮动桢,返回浮动桢
///
///
///
public static string[] DealWithIFrame(string url, string content)
{
string regiFrame = @"