using System;
using System.Data;
using System.Data.OleDb;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Text.RegularExpressions;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Zone
{
//*****************************【LibCommon v 1.0】 2011.5.6 拆分lib 将web使用大部分拆分出来 **********************************
/// <summary>
/// TcpSocket通信,用于从web等终端发送请求到指定的ip端口,得到返回的数据
/// </summary>
public class TcpSocket
{
public void WebSend_GetMsg(string Ip , string Port , string SendMsg , ref string GetMsg , ref string StateMsg)
{
IPAddress serverIp = IPAddress.Parse(Ip);
IPEndPoint ipEndpoint = new IPEndPoint(serverIp, int.Parse(Port)); //new IPEndPoint(address[0], 6464);
Socket IPsocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
IPsocket.Connect(ipEndpoint);
}
catch
{
StateMsg = "Socket 连接失败!";
}
//Socket连接服务器
if (IPsocket.Connected)
StateMsg = "Socket 正确连接!";
Byte[] ByteGet = Encoding.Default.GetBytes(SendMsg);
IPsocket.Send(ByteGet, ByteGet.Length, 0);
//
//Int32 rBytes = IPsocket.Receive(RecvBytes, RecvBytes.Length, 0);
Byte[] RecvBytes = new Byte[1024];
Int32 rBytes = IPsocket.Receive(RecvBytes);
StateMsg = "接收字节数:" + rBytes.ToString();
String ss = null;
//ss = Encoding.Default.GetString(RecvBytes);// ASCII.GetString(RecvBytes, 0, rBytes);
ss = Encoding.Default.GetString(RecvBytes, 0, rBytes);
GetMsg = ss;
IPsocket.Shutdown(SocketShutdown.Both);
IPsocket.Close();
}
}
//常用的一些函数
public class FuncComm
{
public FuncComm()
{
}
/// <summary>
/// 给RadioButtonList添加性别
/// </summary>
/// <param name="rbl"></param>
/// <param name="IsShowUnknowSex"></param>
/// <param name="SexString"></param>
public void SexAdd(ref RadioButtonList rbl, bool IsShowUnknowSex,string SexString)
{
if (rbl == null) return;
rbl.Items.Clear();
if (IsShowUnknowSex==true) rbl.Items.Add(new ListItem("未知", "0"));
rbl.Items.Add(new ListItem("男","1"));
rbl.Items.Add(new ListItem("女","2"));
rbl.Items[0].Selected = true;
if (SexString != null && SexString != "")
{
for(int i=0;i<rbl.Items.Count;i++)
{
if (SexString == rbl.Items[i].Value.ToString())
{
rbl.Items[i].Selected = true;
return;
}
}
}
}
/// <summary>
/// 打印出Asp.net验证控件使用到的正则表达式的代码
/// </summary>
public void RegularCodeShow()
{
//Msg.c1("必须是数字 :[0-9]");
//Msg.c1("任意字符及固定个数 :.{3}");
//Msg.c1("任意字符及伸缩个数 :.{0,3}");
//Msg.c1("数字字母范围内6到20个 :[0-9a-zA-Z]{6,20}");
//Msg.c1(@"11位的手机号码 :\d{11}");
//Msg.c1(@"是否是日期 :\d{4}-\d{1,2}-\d{1,2}");
//Msg.c1(@"判断货币类型 : (\d{1,5})(\.\d{1,2})?");
//Msg.c1(@"必须为汉字 : [\u4e00-\u9fa5]{1,3}");
//Msg.c1(@"字母数字下划线汉字 : [\u4e00-\u9fa5a-zA-Z_0-9]{1,3}");
//Msg.c1(@"搜寻样式代码 : style='.+\'");
}
/// <summary>
/// 单独调用fc.IsBeyoundDate(b, c, "d", 3)检查时间是否错误,得出bool值,则检查限定时间段是否超出
/// </summary>
/// <param name="StarTime"></param>
/// <param name="EndTime"></param>
/// <param name="DateType">h,d,m,</param>
/// <param name="Long"></param>
/// <returns></returns>
public bool IsBeyoundDate(string StarTime,string EndTime,string DateType,int Long)
{
bool bl = false;
DateTime STime = new DateTime(), ETime = new DateTime(), LastTime = new DateTime();
try
{
STime = DateTime.Parse(StarTime);
ETime = DateTime.Parse(EndTime);
}
catch
{
}
switch (DateType)
{
case "h":
LastTime = STime.AddHours(Long);
break;
case "d":
LastTime = STime.AddDays(Long);
break;
case "m":
LastTime = STime.AddMonths(Long);
break;
default:
break;
}
if (ETime > LastTime ) bl = true;
return bl;
}
/// <summary>
/// 将字符串里的正斜杠,转化为反斜杠
/// </summary>
/// <param name="aaa"></param>
/// <returns></returns>
public string GetFanXieGang(string aaa)
{
string ok = "";
aaa = aaa.Replace("\\","/");
ok = aaa;
//aaa = aaa.Replace(char.ConvertFromUtf32(092).ToString(),char.ConvertFromUtf32(047));
return ok;
}
/// <summary>
/// 去掉字符串最右边的,号,例: "1,2,3,"->"1,2,3"
/// </summary>
/// <param name="str"></param>
/// <param name="code"></param>
/// <returns></returns>
public string ReplaceRightComma(string str, string code)
{
string ok = str;
for (int i = 0; i < str.Length; i++)
{
if (ok.Substring(ok.Length - 1, 1) == code || ok.Substring(ok.Length - 1, 1) == " ")
{
ok = ok.Substring(0, ok.Length - 1);
}
else
{
break;
}
}
return ok;
}
/// <summary>
/// 用特定的符号分割字符串,得出数组里面的某个i位置的字符串
/// </summary>
/// <param name="str"></param>
/// <param name="Arr_i"></param>
/// <returns></returns>
public string GetArrStr(string str, int Arr_i,char SplitCode)
{
string ok = "";
if (str == null) return "";
str = str.Replace(" ", "");
string[] arr = str.Split(SplitCode);
ok = arr[Arr_i];
return ok;
}
/// <summary>
/// 数字转化成为对应的字符串,如0-未注册用户 1-注册用户等,WhichType(商家级别/UserVIPLevel)
/// </summary>
/// <param name="Int"></param>
/// <param name="WhichType">商家级别</param>
/// <returns></returns>
public string IntToName(string IntStr,string WhichType)
{
string ok = "";
if (IntStr == null) return "";
switch (WhichType)
{
case "终端类型":
if (IntStr == "0") ok = "普通";
if (IntStr == "1") ok = "智能";
break;
case "性别":
if (IntStr == "0") ok = "未知";
if (IntStr == "1") ok = "男";
if (IntStr == "2") ok = "女";
break;
case "号码品牌":
if (IntStr == "1") ok = "全球通";
if (IntStr == "2") ok = "神州行";
if (IntStr == "3") ok = "动感地带";
if (IntStr == "4") ok = "大众卡";
break;
case "ptt状态":
if (IntStr == "0") ok = "正常";
if (IntStr == "1") ok = "过期";
if (IntStr == "2") ok = "注销";
break;
case "会议状态":
if (IntStr == "0") ok = "未召开";
if (IntStr == "1") ok = "正在开";
if (IntStr == "2") ok = "完毕";
break;
case "是否到席":
if (IntStr == "0") ok = "未到席";
if (IntStr == "1") ok = "到席";
if (IntStr == "2") ok = "完毕";
break;
case "呼叫类型":
if (IntStr == "0") ok = "手机";
if (IntStr == "1") ok = "短信";
if (IntStr == "2") ok = "web";
if (IntStr == "3") ok = "智能手机";
break;
default:
ok = "";
break;
}
return ok;
}
/// <summary>
/// 将商家的积分转化为星级的显示
/// </summary>
/// <param name="Score"></param>
/// <returns></returns>
public string GetBizScoreToStar(string ScoreStr)
{
string ok = "";
if (IsNumber(ScoreStr) == false) return "";
long Score = Convert.ToInt64(ScoreStr);
if (Score > 0 && Score < 200) ok = "☆";
if (Score >= 200 && Score < 300) ok = "★";
if (Score >= 300 && Score < 400) ok = "★☆";
if (Score >= 400 && Score < 500) ok = "★★";
if (Score >= 500 && Score < 600) ok = "★★☆";
if (Score >= 600 && Score < 700) ok = "★★★";
if (Score >= 700 && Score < 800) ok = "★★★☆";
if (Score >= 800 && Score < 900) ok = "★★★★";
if (Score >= 900 && Score < 1000)ok = "★★★★☆";
if (Score >= 1000 ) ok = "★★★★★";
return ok;
}
/// <summary>
/// 截断字符串,将超出指定长度后面的字符串用...进行省略,如果Len为零,则截断不添加"..."
/// </summary>
/// <param name="Str">例:“你的生命如此多情遇见了你”-> “你的生命...”</param>
/// <param name="Len">例:4</param>
/// <returns></returns>
public string ShortStr(string Str, int Len,bool IsDot)
{
string FixStr = null;
FixStr = Str;
if (Str.Length >= Len)
{
string Dot = "";
if (IsDot) Dot = "...";
FixStr = Str.Substring(0, Len) + Dot;
}
return FixStr;
}
public string GetMd5(string str)
{
string str2 = FormsAuthentication.HashPasswordForStoringInConfigFile(str,"md5");
return str2;
}
/// 检查字符串是否含有'""等非法字符,进行过滤
/// </summary>
/// <param name="Str">例:"This is =1'or '1'= '1"等</param>
/// <returns>返回过滤后的字符串</returns>
public string CkStr(string Str)
{
if (Str != "" || Str != null)
{
Str = Str.Replace("'", "");
return Str;
}
return Str;
}
public void PageDownUp(object sender, EventArgs e,ref GridView gv)
{
try
{
string arg = ((LinkButton)sender).CommandArgument.ToString();
switch (arg)
{
case "fist":
gv.PageIndex = 0;
break;
case "prev":
if (gv.PageIndex > 0)
{
gv.PageIndex -= 1;
}
break;
case "next":
if (gv.PageIndex < (gv.PageCount - 1))
{
gv.PageIndex += 1;
}
break;
case "last":
if (gv.PageCount == 0)
{
gv.PageIndex = 0;
}
else
{
gv.PageIndex = (gv.PageCount - 1);
}
break;
default:
gv.PageIndex = 0;
break;
}
}
catch (Exception ex)
{
throw ex;//Msg.c2(ex.Message);
}
}
Random rand = new Random();
/// <summary>
/// CreateRandomCode是自定义的函数,参数代表验证码位数
/// </summary>
/// <param name="codeCount"></param>
/// <returns></returns>
public string CreateRandomCode(int codeCount)
{
string allChar = "1,2,3,4,5,6,7,8,9,0" ;
string[] allCharArray = allChar.Split(',');
string randomCode = "";
int temp = -1;
//Random rand = new Random();
for(int i = 0; i < codeCount; i++)
{
if(temp != -1)
{
rand = new Random(i*temp*((int)DateTime.Now.Ticks));
}
int t = rand.Next(10);
if(temp == t)
{
return CreateRandomCode(codeCount);
}
temp = t ;
randomCode += allCharArray[t];
}
return randomCode;
}
/// <summary>
/// CreateRandomCodeInt是自定义的函数,返回纯数字的随机数
/// </summary>
/// <param name="codeCount"></param>
/// <returns></returns>
///
public string CreateRandomCodeInt(int codeCount)
{
string allChar = "1,2,3,4,5,6,7,8,9,0" ;
string[] allCharArray = allChar.Split(',');
string randomCode = "";
int temp = -1;
//Random rand = new Random();
for(int i = 0; i < codeCount; i++)
{
if(temp != -1)
{
rand = new Random(i*temp*((int)DateTime.Now.Ticks));
}
int t = rand.Next(10);
if(temp == t)
{
return CreateRandomCodeInt(codeCount);
}
temp = t;
randomCode += allCharArray[t];
}
return randomCode;
}
/// <summary>
/// 验证是否是数字,中间用","隔开,例: 1001,1002,1003,并计算出其中的个数
/// </summary>
/// <param name="oText"></param>
/// <returns></returns>
public static bool IsNumber(string oText)
{
if (oText == null) return false;
oText.Trim();
string[] arr = oText.Split(',');
try
{
foreach (string a in arr)
{
long var1 = Convert.ToInt64(a);
}
return true;
}
catch
{
return false;
}
}
/// <summary>
/// 验证是否是数字,中间用","隔开,例: 1001,1002,1003
/// </summary>
/// <param name="oText"></param>
/// <param name="it"></param>
/// <returns></returns>
public static bool IsNumber(string oText, ref int it)
{
if (oText == null) return false;
oText.Trim();
string[] arr = oText.Split(',');
try
{
foreach (string a in arr)
{
long var1 = Convert.ToInt64(a);
}
it = arr.Length;
return true;
}
catch
{
return false;
}
}
/// <summary>
/// 做为测试用的
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public string SortStr(string str)
{
string pattern = "[^0-9a-zA-Z\u4e00-\u9fa5]";
Regex r = new Regex(pattern, RegexOptions.Compiled);
str = r.Replace( str, "");
return str;
}
/// <summary>
/// 将"'等非法字符进行编码转化
/// </summary>
/// <param name="strText"></param>
/// <returns></returns>
public string GetEnCodeStr(string strText)
{
strText = strText.Replace("<","<"); //左<
strText = strText.Replace(">",">"); //右>
strText = strText.Replace(";",";") ; //分号
strText = strText.Replace("'","'") ; //'单引号
strText = strText.Replace("\"","""); //“双引号
strText = strText.Replace(char.ConvertFromUtf32(9)," ") ; //'空格
strText = strText.Replace(char.ConvertFromUtf32(10),"<br>") ; //换行
strText = strText.Replace(char.ConvertFromUtf32(13),""); //回车
strText = strText.Replace(char.ConvertFromUtf32(32)," "); //空格
strText = strText.Replace(char.ConvertFromUtf32(34),"""); //双引号
strText = strText.Replace(char.ConvertFromUtf32(39),"'"); //单引号
strText = strText.Replace("script","script"); //script
strText = strText.Replace("(","("); //左(
strText = strText.Replace(")",")"); //右)
strText = strText.Replace("--","--"); //SQL注释符
return strText;
}
/// <summary>
/// 编辑模式下,将<,; 等编码字符转换回<,>,<br>
/// </summary>
/// <param name="strText"></param>
/// <returns></returns>
public string GetDeCodeStr(string strText)
{
strText = strText.Replace("<","<"); //左<
strText = strText.Replace(">",">"); //右>
strText = strText.Replace(";",";") ; //分号
strText = strText.Replace("'","'") ; //'单引号
strText = strText.Replace(""","\""); //“双引号
strText = strText.Replace(" ",char.ConvertFromUtf32(9)) ; //'空格
strText = strText.Replace("<br>",char.ConvertFromUtf32(10)) ; //换行
strText = strText.Replace(" ",char.ConvertFromUtf32(32)); //空格
strText = strText.Replace(""",char.ConvertFromUtf32(34)); //双引号
strText = strText.Replace("'",char.ConvertFromUtf32(39)); //单引号
strText = strText.Replace("script","script"); //script
strText = strText.Replace("(","("); //左(
strText = strText.Replace(")",")"); //右)
strText = strText.Replace("--","--"); //SQL注释符
return strText;
}
/// <summary>
/// 将sql注入的非法字符替换空
/// </summary>
/// <param name="strText"></param>
public string RepalceSqlCode(string strText)
{
strText = strText.Replace("<",""); //左<
strText = strText.Replace(">",""); //右>
strText = strText.Replace(";","") ; //分号
strText = strText.Replace("'","") ; //'单引号
strText = strText.Replace("\"",""); //“双引号
strText = strText.Replace(char.ConvertFromUtf32(9),"") ; //'空格
strText = strText.Replace(char.ConvertFromUtf32(10),"") ; //换行
strText = strText.Replace(char.ConvertFromUtf32(13),""); //回车
strText = strText.Replace(char.ConvertFromUtf32(32),""); //空格
strText = strText.Replace(char.ConvertFromUtf32(34),""); //双引号
strText = strText.Replace(char.ConvertFromUtf32(39),""); //单引号
strText = strText.Replace("(",""); //左(
strText = strText.Replace(")",""); //右)
strText = strText.Replace("-",""); //SQL注释符
return strText;
}
/// <summary>
/// 返回一个时间+随机字符串,例:20070203093015ABCDEF
/// </summary>
/// <returns></returns>
public string GetRndID()
{
string tm = GetTimeStr() + CreateRandomCode(6);
return tm;
}
/// <summary>
///
/// </summary>
/// <param name="IsInt"></param>
/// <param name="CodeLen"></param>
/// <returns></returns>
public string GetRndID(bool IsInt,int CodeLen)
{
string tm = GetTimeStr() + CreateRandomCodeInt(CodeLen);
return tm;
}
/// <summary>
/// 返回纯数字的时间 例:20070203093015
/// </summary>
/// <returns></returns>
public string GetTimeStr()
{
string tm = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss",DateTimeFormatInfo.InvariantInfo);
tm = tm.Replace(" ", "");tm = tm.Replace(":", "");tm = tm.Replace("-", "");
return tm;
}
/// <summary>
/// 将字符串类型的格式时间转换为纯数字时间 例:20070203093015
/// </summary>
/// <param name="tm"></param>
/// <returns></returns>
public string GetTimeStr(string tm)
{
tm = tm.Replace(" ", "");tm = tm.Replace(":", "");tm = tm.Replace("-", "");
return tm;
}
/// <summary>
/// 返回时间差的纯数字时间 例:20070203093015
/// </summary>
/// <param name="tm"></param>
/// <returns></returns>
public string GetTimeStr(DateTime tmt)
{
string tm = tmt.ToString("yyyy-MM-dd HH:mm:ss",DateTimeFormatInfo.InvariantInfo);
tm = tm.Replace(" ", "");tm = tm.Replace(":", "");tm = tm.Replace("-", "");
return tm;
}
public string ShowEachDateFormate()
{
string ReturnStr = "";
DateTime dt = DateTime.Now;
String[] format = {
"d", "D",
"f", "F",
"g", "G",
"m",
"r",
"s",
"t", "T",
"u", "U",
"y",
"dddd, MMMM dd yyyy",
"ddd, MMM d \"'\"yy",
"dddd, MMMM dd",
"M/yy",
"dd-MM-yy",
"yyyy-MM-dd HH:mm:ss",
};
String date;
for (int i = 0; i < format.Length; i++)
{
date = dt.ToString(format[i], DateTimeFormatInfo.InvariantInfo);
//Msg.c1((String.Concat(format[i], " :" , date))+"</br>");
ReturnStr += "date \\n";
}
return ReturnStr;
}
/// <summary>
/// 检查um是不是11位的 135-139之间的移动手机号码,包括159
/// </summary>
/// <param name="um"></param>
/// <returns></returns>
public bool IsMobile(string um)
{
um = um.Trim();
bool bl = false;
try
{
if (IsNumber(um))
{
int i = Convert.ToInt32(um.Substring(0,3));
if (um.Length == 11)
{
if ((i >= 130) && (i <= 139)) bl = true;
if ((i >= 154) && (i <= 159)) bl = true;
}
}
return bl;
}
catch
{
return bl;
}
}
/// <summary>
/// 给查询到的模糊关键字标红
/// </summary>
/// <param name="KeyStr"></param>
/// <returns></returns>
public string MarkRed(string Content,string KeyStr)
{
if (Content.IndexOf(KeyStr) >= 0)
{
Content = Content.Replace(KeyStr,"<font color=red>" + KeyStr + "</font>");
}
return Content;
}
}
/// <summary>
/// 读取服务器上的xls|txt文件,导入到数据库中
/// </summary>
public class ImportDB
{
/// <summary>
/// 将指定Excel文件中的数据转换成DataTable对象,供应用程序进一步处理
/// </summary>
/// <param name="filePath"></param>
/// <returns></returns>
public DataTable Import(string filePath)
{
DataTable dt = new DataTable();
bool canOpen = false;
string ConnStr = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + filePath + ";" + "Extended Properties=\"Excel 8.0;\"";
OleDbConnection conn2 = new OleDbConnection(ConnStr);
//Msg.c1(ConnStr);
try//尝试数据连接是否可用
{
conn2.Open();
conn2.Close();
canOpen = true;
}
catch (Exception ex)
{
throw ex;
}
if (canOpen)
{
try//如果数据连接可以打开则尝试读入数据
{
OleDbCommand myOleDbCommand = new OleDbCommand("SELECT * FROM [Sheet1$]", conn2);
OleDbDataAdapter myData = new OleDbDataAdapter(myOleDbCommand);
myData.Fill(dt);
conn2.Close();
}
//如果数据连接可以打开但是读入数据失败,则从文件中提取出工作表的名称,再读入数据
catch
{
string sheetName = GetSheetName(filePath);
if (sheetName.Length > 0)
{
OleDbCommand myOleDbCommand = new OleDbCommand("SELECT * FROM [" + sheetName + "$]", conn2);
OleDbDataAdapter myData = new OleDbDataAdapter(myOleDbCommand);
myData.Fill(dt);
conn2.Close();
}
}
}
else
{
System.IO.StreamReader tmpStream = File.OpenText(filePath);
string tmpStr = tmpStream.ReadToEnd();
tmpStream.Close();
dt = GetDataTableFromString(tmpStr);
tmpStr = "";
}
return dt;
}
/// <summary>
/// 将指定Html字符串的数据转换成DataTable对象 --根据“<tr><td>”等特殊字符进行处理
/// </summary>
/// <param name="tmpHtml">Html字符串</param>
/// <returns></returns>
private static DataTable GetDataTableFromString(string tmpHtml)
{
string tmpStr = tmpHtml;
DataTable TB = new DataTable();
//先处理一下这个字符串,删除第一个<tr>之前合最后一个</tr>之后的部分
int index = tmpStr.IndexOf("<tr");
if (index > -1)
tmpStr = tmpStr.Substring(index);
else
return TB;
index = tmpStr.LastIndexOf("</tr>");
if (index > -1)
tmpStr = tmpStr.Substring(0, index + 5);
else
return TB;
bool existsSparator = false;
char Separator = Convert.ToChar("^");
//如果原字符串中包含分隔符“^”则先把它替换掉
if (tmpStr.IndexOf(Separator.ToString()) > -1)
{
existsSparator = true;
tmpStr = tmpStr.Replace("^", "^$&^");
}
//先根据“</tr>”分拆
string[] tmpRow = tmpStr.Replace("</tr>", "^").Split(Separator);
for (int i = 0; i < tmpRow.Length - 1; i++)
{
DataRow newRow = TB.NewRow();
string tmpStrI = tmpRow[i];
if (tmpStrI.IndexOf("<tr") > -1)
{
tmpStrI = tmpStrI.Substring(tmpStrI.IndexOf("<tr"));
if (tmpStrI.IndexOf("display:none") < 0 || tmpStrI.IndexOf("display:none") > tmpStrI.IndexOf(">"))
{
tmpStrI = tmpStrI.Replace("</td>", "^");
string[] tmpField = tmpStrI.Split(Separator);
for (int j = 0; j < tmpField.Length - 1; j++)
{
tmpField[j] = RemoveString(tmpField[j], "<font>");
index = tmpField[j].LastIndexOf(">") + 1;
if (index > 0)
{
string field = tmpField[j].Substring(index, tmpField[j].Length - index);
if (existsSparator) field = field.Replace("^$&^", "^");
if (i == 0)
{
string tmpFieldName = field;
int sn = 1;
while (TB.Columns.Contains(tmpFieldName))
{
tmpFieldName = field + sn.ToString();
sn += 1;
}
TB.Columns.Add(tmpFieldName);
}
else
{
newRow[j] = field;
}
}//end of if(index>0)
}
if (i > 0)
TB.Rows.Add(newRow);
}
}
}
TB.AcceptChanges();
return TB;
}
/// <summary>
/// 从指定Html字符串中剔除指定的对象
/// </summary>
/// <param name="tmpHtml">Html字符串</param>
/// <param name="remove">需要剔除的对象--例如输入"<font>"则剔除"<font ???????>"和"</font>>"</param>
/// <returns></returns>
public static string RemoveString(string tmpHtml, string remove)
{
tmpHtml = tmpHtml.Replace(remove.Replace("<", "</"), "");
tmpHtml = RemoveStringHead(tmpHtml, remove);
return tmpHtml;
}
/// <summary>
/// 从指定Html字符串中剔除指定的对象
/// </summary>
/// <param name="tmpHtml">Html字符串</param>
/// <param name="remove">需要剔除的对象--例如输入"<font>"则剔除"<font ???????>"和"</font>>"</param>
/// <returns></returns>
private static string RemoveStringHead(string tmpHtml, string remove)
{
//为了方便注释,假设输入参数remove="<font>"
if (remove.Length < 1) return tmpHtml;//参数remove为空:不处理返回
if ((remove.Substring(0, 1) != "<") || (remove.Substring(remove.Length - 1) != ">")) return tmpHtml;//参数remove不是<?????>:不处理返回
int IndexS = tmpHtml.IndexOf(remove.Replace(">", ""));//查找“<font”的位置
int IndexE = -1;
if (IndexS > -1)
{
string tmpRight = tmpHtml.Substring(IndexS, tmpHtml.Length - IndexS);
IndexE = tmpRight.IndexOf(">");
if (IndexE > -1)
tmpHtml = tmpHtml.Substring(0, IndexS) + tmpHtml.Substring(IndexS + IndexE + 1);
if (tmpHtml.IndexOf(remove.Replace(">", "")) > -1)
tmpHtml = RemoveStringHead(tmpHtml, remove);
}
return tmpHtml;
}
/// <summary>
/// 将指定Excel文件中读取第一张工作表的名称
/// </summary>
/// <param name="filePath"></param>
/// <returns></returns>
private static string GetSheetName(string filePath)
{
string sheetName = "";
System.IO.FileStream tmpStream = File.OpenRead(filePath);
byte[] fileByte = new byte[tmpStream.Length];
tmpStream.Read(fileByte, 0, fileByte.Length);
tmpStream.Close();
byte[] tmpByte = new byte[]{Convert.ToByte(11),Convert.ToByte(0),Convert.ToByte(0),Convert.ToByte(0),Convert.ToByte(0),Convert.ToByte(0),Convert.ToByte(0),Convert.ToByte(0),
Convert.ToByte(11),Convert.ToByte(0),Convert.ToByte(0),Convert.ToByte(0),Convert.ToByte(0),Convert.ToByte(0),Convert.ToByte(0),Convert.ToByte(0),
Convert.ToByte(30),Convert.ToByte(16),Convert.ToByte(0),Convert.ToByte(0)};
int index = GetSheetIndex(fileByte, tmpByte);
if (index > -1)
{
index += 16 + 12;
System.Collections.ArrayList sheetNameList = new System.Collections.ArrayList();
for (int i = index; i < fileByte.Length - 1; i++)
{
byte temp = fileByte[i];
if (temp != Convert.ToByte(0))
sheetNameList.Add(temp);
else
break;
}
byte[] sheetNameByte = new byte[sheetNameList.Count];
for (int i = 0; i < sheetNameList.Count; i++)
sheetNameByte[i] = Convert.ToByte(sheetNameList[i]);
sheetName = System.Text.Encoding.Default.GetString(sheetNameByte);
}
return sheetName;
}
/// <summary>
/// 只供方法GetSheetName()使用
/// </summary>
/// <returns></returns>
private static int GetSheetIndex(byte[] FindTarget, byte[] FindItem)
{
int index = -1;
int FindItemLength = FindItem.Length;
if (FindItemLength < 1) return -1;
int FindTargetLength = FindTarget.Length;
if ((FindTargetLength - 1) < FindItemLength) return -1;
for (int i = FindTargetLength - FindItemLength - 1; i > -1; i--)
{
System.Collections.ArrayList tmpList = new System.Collections.ArrayList();
int find = 0;
for (int j = 0; j < FindItemLength; j++)
{
if (FindTarget[i + j] == FindItem[j]) find += 1;
}
if (find == FindItemLength)
{
index = i;
break;
}
}
return index;
}
/// <summary>
/// 调用cmd命令,执行dos下命令,如:dir,bcp,返回执行后的字符串
/// </summary>
/// <param name="commandText"></param>
/// <returns></returns>
public static string ExeCommand(string commandText)
{
Process p = new Process();
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.CreateNoWindow = true;
string strOutput = null;
try
{
p.Start();
p.StandardInput.WriteLine(commandText);
p.StandardInput.WriteLine("exit");
strOutput = p.StandardOutput.ReadToEnd();
p.WaitForExit();
p.Close();
}
catch (Exception e)
{
strOutput = e.Message;
}
return strOutput;
}
/// <summary>
/// 调用cmd命令,然后从返回的string里比较看是否命令执行成功
/// </summary>
/// <param name="CmpStr"></param>
/// <param name="commandText"></param>
/// <returns></returns>
public static bool IsBcpOk(string commandText, string CmpStr)
{
bool bl = false;
string str = ExeCommand(commandText);
if (commandText.Contains(CmpStr)) bl = true;
return bl;
}
}
/// <summary>
/// 导出数据到txt,Excel等
/// 特别注意添加代码 public override void VerifyRenderingInServerForm(Control control){}到页面中,否则报错
/// 代码示例如下,注意顺序:
/// ed.Sele_GridViewData(ref gvUsers, true, "")
/// BindData();
/// ed.DisableControls(gvUsers)
/// ed.Export_To_Excle(ref gvUsers);
/// </summary>
public class ExportData
{
public void Sele_GridViewData(ref GridView gv, bool IsPagingData, string HiddenColumnsNumbers)
{
FuncComm fc = new FuncComm();
if (HiddenColumnsNumbers != null && HiddenColumnsNumbers != "")
{
foreach (string s in HiddenColumnsNumbers.Split(','))
{
gv.Columns[int.Parse(s)].Visible = false;
}
}
gv.PagerSettings.Visible = false;
gv.AllowPaging = IsPagingData;
}
public void Exporting_DataStyle(ref GridViewRowEventArgs e, string AddCssColumnsNumbers,string ClassName)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (AddCssColumnsNumbers != null && AddCssColumnsNumbers != "")
{
foreach (string s in AddCssColumnsNumbers.Split(','))
{
e.Row.Cells[int.Parse(s)].Attributes.Add("class", ClassName);
}
}
//e.Row.Cells[1].Attributes.Add("style", "vnd.ms-excel.numberformat:@");
//e.Row.Cells[3].Attributes.Add("style", "vnd.ms-excel.numberformat:¥#,###.00");
}
}
public void Export_To_Excle(ref GridView gv)
{
//if (Is_DisableControls == true) DisableControls(ref gv);
string style = @"<style> .text { mso-number-format:'\@';mso-ignore:colspan}
.text1 { mso-number-format:\@; }
.text2 { vnd.ms-excel.numberformat:@;}
.money { vnd.ms-excel.numberformat:¥#,###.00;}
</style> ";
System.Web.HttpContext.Current.Response.ClearContent();
System.Web.HttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename=MyExcelFile.xls");
System.Web.HttpContext.Current.Response.ContentType = "application/excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
//BindData(true);
gv.RenderControl(htw);
System.Web.HttpContext.Current.Response.Write(style);
System.Web.HttpContext.Current.Response.Write(sw.ToString());
System.Web.HttpContext.Current.Response.End();
}
public void DisableControls(Control gv)
{
LinkButton lb = new LinkButton();
Literal l = new Literal();
string name = String.Empty;
for (int i = 0; i < gv.Controls.Count; i++)
{
if (gv.Controls[i].GetType() == typeof(LinkButton))
{
l.Text = (gv.Controls[i] as LinkButton).Text;
gv.Controls.Remove(gv.Controls[i]);
gv.Controls.AddAt(i, l);
}
else if (gv.Controls[i].GetType() == typeof(DropDownList))
{
l.Text = (gv.Controls[i] as DropDownList).SelectedItem.Text;
gv.Controls.Remove(gv.Controls[i]);
gv.Controls.AddAt(i, l);
}
if (gv.Controls[i].HasControls())
{
DisableControls(gv.Controls[i]);
}
}
}
}
/// <summary>
/// 日志管理,检查日志文件是否存在,建立新文件
/// </summary>
public class LogMana
{
/// <summary>
/// 检查文件大小,如果文件过大的话,就重新建立个新的日志文件
/// </summary>
/// <param name="path">路径</param>
/// <param name="vfile">要校验的文件</param>
public static void CkFile_Rename(string path,string vfile)
{
//Edti Jarry: 通用性 path = System.Web.HttpContext.Current.Server.MapPath(path);
DirectoryInfo di = new DirectoryInfo(path);
if (di.Exists == false) di.Create();
if (File.Exists(path + "\\" + vfile))
{
FileInfo fi = new FileInfo(path + "\\" + vfile);
long len = fi.Length;
if (len > 204800)
{
vfile = DateTime.Now.ToString("yyyy-MM-dd") + "_" + vfile;
File.Create(path + "\\" + vfile);
}
}
else
{
File.Create(path + "\\" + vfile);
}
}
/// <summary>
/// 将日志信息写入到指定的文本文件中
/// </summary>
/// <param name="message">日志信息</param>
/// <param name="Fpath">指定的文件夹路径</param>
/// <param name="FileName">指定的日志文件名称</param>
/// <param name="IsShowTime">是否显示时间</param>
/// <param name="IsAutoDay">否则自动每天记录一个</param>
public static void WriteText(string message, string Fpath, string FileName,bool IsShowTime,bool IsAutoDay)
{
string filepath = "";
//Edti Jarry: 通用性,去掉此句 Fpath = System.Web.HttpContext.Current.Server.MapPath(Fpath);
DirectoryInfo di = new DirectoryInfo(Fpath); if (di.Exists == false) di.Create();
if (IsAutoDay) FileName = DateTime.Now.ToString("yyyy-MM-dd") + "_" + FileName; ;
filepath = Fpath + FileName;
try
{
//方法一:写文本文件.txt
StreamWriter writer = null;
if (File.Exists(filepath))
{
writer = File.AppendText(filepath);
}
else
{
writer = File.CreateText(filepath);
}
if (IsShowTime) message = "【" + DateTime.Now.ToString() + "】:" + message;
writer.WriteLine(message);
writer.Close();
}
catch (Exception ex)
{
try
{
StreamWriter writer = null;
if (File.Exists(filepath))
{
writer = File.AppendText(filepath);
}
else
{
writer = File.CreateText(filepath);
}
if (IsShowTime) message = "【" + DateTime.Now.ToString() + "】:" + ex.Message;
writer.WriteLine(message);
writer.Close();
}
catch { }
}
}
/// <summary>
/// 将日志信息写入到指定的文本文件中
/// </summary>
/// <param name="message"></param>
public static void WriteText(string message,string Fpath)
{
string filepath = "", FileName = "Log.txt";
bool IsShowTime = true, IsAutoDay = true;
Fpath = Fpath + @"/LogFile/";
DirectoryInfo di = new DirectoryInfo(Fpath); if (di.Exists == false) di.Create();
if (IsAutoDay) FileName = DateTime.Now.ToString("yyyy-MM-dd") + "_" + FileName; ;
filepath = Fpath + FileName;
try
{
//方法一:写文本文件.txt
StreamWriter writer = null;
if (File.Exists(filepath))
{
writer = File.AppendText(filepath);
}
else
{
writer = File.CreateText(filepath);
}
if (IsShowTime) message = "【" + DateTime.Now.ToString() + "】:" + message;
writer.WriteLine(message);
writer.Close();
}
catch (Exception ex)
{
try
{
StreamWriter writer = null;
if (File.Exists(filepath))
{
writer = File.AppendText(filepath);
}
else
{
writer = File.CreateText(filepath);
}
if (IsShowTime) message = "【" + DateTime.Now.ToString() + "】:" + ex.Message;
writer.WriteLine(message);
writer.Close();
}
catch { }
}
}
}
}