using System; using System.Data; using System.Web; using System.Text.RegularExpressions; using System.Collections; using System.Net; using System.Text; using System.IO; using BP.Sys; using System.ServiceModel; using System.ServiceModel.Channels; using System.Xml; using BP.Web; using BP.Difference; namespace BP.DA { /// /// DataType 的摘要说明。 /// public class DataType { public static bool IsNullOrEmpty(string s) { if (s == null || s.Equals("") == true || s.Equals("null") == true || s.Equals("undefined") == true) return true; return false; } /// /// 比较两个字符串是否有交集 /// /// /// /// public static bool IsHaveIt(string ids1, string ids2) { if (DataType.IsNullOrEmpty(ids1) == true) return false; if (DataType.IsNullOrEmpty(ids2) == true) return false; string[] str1s = ids1.Split(','); string[] str2s = ids2.Split(','); foreach (string str1 in str1s) { if (str1 == "" || str1 == null) continue; foreach (string str2 in str2s) { if (str2 == "" || str2 == null) continue; if (str2.Equals(str1) == true) return true; } } return false; } #region 与日期相关的操作. /// /// 获得指定日期的周1第一天日期. /// /// 指定的日期 /// public static DateTime WeekOfMonday(DateTime dt) { if (dt.DayOfWeek == DayOfWeek.Monday) return DataType.ParseSysDate2DateTime(dt.ToString("yyyy-MM-dd") + " 00:01"); for (int i = 0; i < 7; i++) { DateTime mydt = dt.AddDays(-i); if (mydt.DayOfWeek == DayOfWeek.Monday) return DataType.ParseSysDate2DateTime(mydt.ToString("yyyy-MM-dd") + " 00:01"); } throw new Exception("@系统错误."); } /// /// 获得指定日期的周7第7天日期. /// /// 指定的日期 /// public static DateTime WeekOfSunday(DateTime dt) { if (dt.DayOfWeek == DayOfWeek.Sunday) return DataType.ParseSysDate2DateTime(dt.ToString("yyyy-MM-dd") + " 00:01"); for (int i = 0; i < 7; i++) { DateTime mydt = dt.AddDays(i); if (mydt.DayOfWeek == DayOfWeek.Sunday) return DataType.ParseSysDate2DateTime(mydt.ToString("yyyy-MM-dd") + " 00:01"); } throw new Exception("@系统错误."); } /// /// 增加日期去掉周末节假日 /// /// 日期 /// 增加的天数 /// public static DateTime AddDays(string dt, int days, TWay tway) { return AddDays(DataType.ParseSysDate2DateTime(dt), days, tway); } /// /// 增加日期去掉周末 /// /// /// /// 返回天数 public static DateTime AddDays(DateTime dt, int days, TWay tway) { if (tway == TWay.AllDays) return dt.AddDays(days); //没有设置节假日. if (DataType.IsNullOrEmpty(BP.Sys.GloVar.Holidays)) { // 2015年以前的算法. dt = dt.AddDays(days); if (dt.DayOfWeek == DayOfWeek.Saturday) return dt.AddDays(2); if (dt.DayOfWeek == DayOfWeek.Sunday) return dt.AddDays(1); return dt; } /* 设置节假日. */ while (days > 0) { if (BP.Sys.GloVar.Holidays.Contains(dt.ToString("MM-dd"))) { dt = dt.AddDays(1); continue; } days--; if (days == 0) break; dt = dt.AddDays(1); } return dt; } /// /// 取指定日期是一年中的第几周 /// /// 给定的日期 /// 数字 一年中的第几周 public static int WeekOfYear(DateTime dtime) { int weeknum = 0; DateTime tmpdate = DateTime.Parse(dtime.Year.ToString() + "-1" + "-1"); DayOfWeek firstweek = tmpdate.DayOfWeek; //if(firstweek) int i = dtime.DayOfYear - 1 + (int)firstweek; weeknum = i / 7; if (i > 0) { weeknum++; } return weeknum; } public static string TurnToJiDuByDateTime(string dt) { if (dt.Length <= 6) throw new Exception("@要转化季度的日期格式不正确:" + dt); string yf = dt.Substring(5, 2); switch (yf) { case "01": case "02": case "03": return dt.Substring(0, 4) + "-03"; case "04": case "05": case "06": return dt.Substring(0, 4) + "-06"; case "07": case "08": case "09": return dt.Substring(0, 4) + "-09"; case "10": case "11": case "12": return dt.Substring(0, 4) + "-12"; default: break; } return null; } #endregion #region 将json转换为DataTable /// /// 将json转换为DataTable /// /// 得到的json /// public static DataTable JsonToDataTable(string json) { return BP.Tools.Json.ToDataTable(json); } #endregion #region Datatable转换为Json /// /// Datatable转换为Json /// /// Datatable对象 /// Json字符串 public static string ToJson(DataTable dt) { StringBuilder jsonString = new StringBuilder(); jsonString.Append("["); DataRowCollection drc = dt.Rows; if (drc.Count > 0) { for (int i = 0; i < drc.Count; i++) { jsonString.Append("{"); for (int j = 0; j < dt.Columns.Count; j++) { string strKey = dt.Columns[j].ColumnName; /**小周鹏修改-2014/11/11----------------------------START**/ // BillNoFormat对应value:{YYYY}-{MM}-{dd}-{LSH4} Format时会产生异常。 if (strKey.Equals("BillNoFormat")) { continue; } /**小周鹏修改-2014/11/11----------------------------END**/ string strValue = drc[i][j].ToString(); Type type = dt.Columns[j].DataType; jsonString.Append("\"" + strKey + "\":"); strValue = String.Format(strValue, type); if (j < dt.Columns.Count - 1) { jsonString.Append("\"" + strValue + "\","); } else { jsonString.Append("\"" + strValue + "\""); } } jsonString.Append("},"); } jsonString.Remove(jsonString.Length - 1, 1); } jsonString.Append("]"); return jsonString.ToString(); } /// /// DataTable转换为Json /// public static string ToJson(DataTable dt, string jsonName) { StringBuilder Json = new StringBuilder(); if (DataType.IsNullOrEmpty(jsonName)) jsonName = dt.TableName; Json.Append("{\"" + jsonName + "\":["); if (dt.Rows.Count > 0) { for (int i = 0; i < dt.Rows.Count; i++) { Json.Append("{"); for (int j = 0; j < dt.Columns.Count; j++) { Type type = dt.Rows[i][j].GetType(); Json.Append("\"" + dt.Columns[j].ColumnName.ToString() + "\":" + String.Format(dt.Rows[i][j].ToString(), type)); if (j < dt.Columns.Count - 1) { Json.Append(","); } } Json.Append("}"); if (i < dt.Rows.Count - 1) { Json.Append(","); } } } Json.Append("]}"); return Json.ToString(); } #endregion /// /// 根据通用的树形结构生成行政机构树形结构 /// /// 通用格式的数据表No,Name,ParentNo列 /// 根目录编号值 /// public static DataTable PraseParentTree2TreeNo(DataTable dtTree, string parentNo) { DataTable dt = new DataTable(); dt.Columns.Add("No", typeof(string)); dt.Columns.Add("Name", typeof(string)); dt.Columns.Add("Grade", typeof(string)); dt.Columns.Add("IsDtl", typeof(string)); dt.Columns.Add("RefNo", typeof(string)); dt.Columns.Add("RefParentNo", typeof(string)); dt = _PraseParentTree2TreeNo(dtTree, dt, parentNo); return dt; } private static DataTable _PraseParentTree2TreeNo(DataTable dtTree, DataTable newDt, string parentNo) { //记录已经转换的数据 System.Collections.Generic.List removeRows = new System.Collections.Generic.List(); //DataTable newDtTree = dtTree.Copy(); //newDtTree.DefaultView.RowFilter = " ParentNo=" + parentNo; //newDtTree = newDtTree.DefaultView.ToTable(); foreach (DataRow row in dtTree.Rows) { if (row["ParentNo"].ToString().Equals(parentNo) || row["No"].ToString().Equals(parentNo)) { DataRow newRow = newDt.NewRow(); newRow["No"] = row["No"].ToString(); newRow["Name"] = row["Name"]; newRow["IsDtl"] = "0"; if (dtTree.Columns.Contains("Idx")) newRow["Grade"] = row["Idx"]; if (dtTree.Columns.Contains("RefNo")) newRow["RefNo"] = row["RefNo"]; else newRow["RefNo"] = row["No"]; newRow["RefParentNo"] = row["ParentNo"]; newDt.Rows.Add(newRow); removeRows.Add(row); } } #region 将原结构数据转换到新的datable 中 //foreach (DataRow row in dtTree.Rows) //{ // if (newDt.Rows.Count == 0) // { // if (!row["IsRoot"].Equals("1")) // continue; // DataRow newRow = newDt.NewRow(); // newRow["No"] = row["No"]; // newRow["Name"] = row["Name"]; // newRow["Grade"] = row["Idx"]; // newRow["IsDtl"] = ""; // newRow["RefNo"] = row["RefNo"]; // newRow["RefParentNo"] = row["ParentNo"]; // newDt.Rows.Add(newRow); // removeRows.Add(row); // } // else // { // foreach (DataRow newDtRow in newDt.Rows) // { // if (row["ParentNo"].Equals(newDtRow["No"])) // { // DataRow newRow = newDt.NewRow(); // newRow["No"] = row["No"]; // newRow["Name"] = row["Name"]; // newRow["Grade"] = row["Idx"]; // newRow["IsDtl"] = ""; // newRow["RefNo"] = row["RefNo"]; // newRow["RefParentNo"] = row["ParentNo"]; // newDt.Rows.Add(newRow); // removeRows.Add(row); // } // } // } //} #endregion 将原结构数据转换到新的datable 中 //移除已经转换的数据 foreach (DataRow row in removeRows) dtTree.Rows.Remove(row); //如果原结构中还有数据就接着转换 if (dtTree.Rows.Count != 0) _PraseParentTree2TreeNo(dtTree, newDt, dtTree.Rows[0]["No"].ToString()); return newDt; } /// /// 转换成MB /// /// /// public static float PraseToMB(long val) { try { return float.Parse(String.Format("{0:##.##}", val / 1048576)); } catch { return 0; } } public static string PraseStringToUrlFileName(string fileName) { if (fileName.LastIndexOf('\\') == -1) { fileName = PraseStringToUrlFileNameExt(fileName, "%", "%25"); fileName = PraseStringToUrlFileNameExt(fileName, "+", "%2B"); fileName = PraseStringToUrlFileNameExt(fileName, " ", "%20"); fileName = PraseStringToUrlFileNameExt(fileName, "/", "%2F"); fileName = PraseStringToUrlFileNameExt(fileName, "?", "%3F"); fileName = PraseStringToUrlFileNameExt(fileName, "#", "%23"); fileName = PraseStringToUrlFileNameExt(fileName, "&", "%26"); fileName = PraseStringToUrlFileNameExt(fileName, "=", "%3D"); fileName = PraseStringToUrlFileNameExt(fileName, " ", "%20"); return fileName; } string filePath = fileName.Substring(0, fileName.LastIndexOf('/')); string fName = fileName.Substring(fileName.LastIndexOf('/')); fName = PraseStringToUrlFileNameExt(fName, "%", "%25"); fName = PraseStringToUrlFileNameExt(fName, "+", "%2B"); fName = PraseStringToUrlFileNameExt(fName, " ", "%20"); fName = PraseStringToUrlFileNameExt(fName, "/", "%2F"); fName = PraseStringToUrlFileNameExt(fName, "?", "%3F"); fName = PraseStringToUrlFileNameExt(fName, "#", "%23"); fName = PraseStringToUrlFileNameExt(fName, "&", "%26"); fName = PraseStringToUrlFileNameExt(fName, "=", "%3D"); fName = PraseStringToUrlFileNameExt(fName, " ", "%20"); return filePath + fName; } private static string PraseStringToUrlFileNameExt(string fileName, string val, string replVal) { fileName = fileName.Replace(val, replVal); fileName = fileName.Replace(val, replVal); fileName = fileName.Replace(val, replVal); fileName = fileName.Replace(val, replVal); fileName = fileName.Replace(val, replVal); fileName = fileName.Replace(val, replVal); fileName = fileName.Replace(val, replVal); fileName = fileName.Replace(val, replVal); return fileName; } /// /// 处理文件名称 /// /// 文件格式 /// 返回合法的文件名 public static string PraseStringToFileName(string fileNameFormat) { char[] strs = "+#?*\"<>/;,-:%~".ToCharArray(); foreach (char c in strs) fileNameFormat = fileNameFormat.Replace(c.ToString(), "_"); strs = ":,。;?".ToCharArray(); foreach (char c in strs) fileNameFormat = fileNameFormat.Replace(c.ToString(), "_"); //去掉空格. while (fileNameFormat.Contains(" ") == true) fileNameFormat = fileNameFormat.Replace(" ", ""); //替换特殊字符. fileNameFormat = fileNameFormat.Replace("\t\n", ""); //处理合法的文件名. StringBuilder rBuilder = new StringBuilder(fileNameFormat); foreach (char rInvalidChar in Path.GetInvalidFileNameChars()) rBuilder.Replace(rInvalidChar.ToString(), string.Empty); fileNameFormat = rBuilder.ToString(); fileNameFormat = fileNameFormat.Replace("__", "_"); fileNameFormat = fileNameFormat.Replace("__", "_"); fileNameFormat = fileNameFormat.Replace("__", "_"); fileNameFormat = fileNameFormat.Replace("__", "_"); fileNameFormat = fileNameFormat.Replace("__", "_"); fileNameFormat = fileNameFormat.Replace("__", "_"); fileNameFormat = fileNameFormat.Replace("__", "_"); fileNameFormat = fileNameFormat.Replace("__", "_"); fileNameFormat = fileNameFormat.Replace(" ", ""); fileNameFormat = fileNameFormat.Replace(" ", ""); fileNameFormat = fileNameFormat.Replace(" ", ""); fileNameFormat = fileNameFormat.Replace(" ", ""); fileNameFormat = fileNameFormat.Replace(" ", ""); fileNameFormat = fileNameFormat.Replace(" ", ""); fileNameFormat = fileNameFormat.Replace(" ", ""); fileNameFormat = fileNameFormat.Replace(" ", ""); if (fileNameFormat.Length > 240) fileNameFormat = fileNameFormat.Substring(0, 240); return fileNameFormat; } /// /// /// /// /// /// public static string PraseAtToInSql(string strs, bool isNumber) { if (DataType.IsNullOrEmpty(strs) == true) return "''"; strs = strs.Replace("@", "','"); strs = strs + "'"; if (strs.Length > 2) strs = strs.Substring(2); if (isNumber) strs = strs.Replace("'", ""); return strs; } /// /// 将文件转化为二进制 /// /// /// public static byte[] ConvertFileToByte(string fileName) { System.IO.FileStream fs = new System.IO.FileStream(fileName, System.IO.FileMode.Open, System.IO.FileAccess.Read, FileShare.ReadWrite); byte[] nowByte = new byte[(int)fs.Length]; try { fs.Read(nowByte, 0, (int)fs.Length); return nowByte; } catch (Exception ex) { throw ex; } finally { fs.Close(); } } /// /// 写文件 /// /// 路径 /// 内容 public static void WriteFile(string file, string Doc) { System.IO.StreamWriter sr; try { if (System.IO.File.Exists(file)) System.IO.File.Delete(file); //sr = new System.IO.StreamWriter(file, false, System.Text.Encoding.GetEncoding("GB2312")); sr = new System.IO.StreamWriter(file, false, System.Text.Encoding.UTF8); } catch (Exception ex) { throw new Exception("@文件:" + file + ",错误:" + ex.Message); } sr.Write(Doc); sr.Close(); } /// /// 写入一个文件 /// /// /// /// public static string WriteFile(string filePathName, byte[] objData) { string folder = System.IO.Path.GetDirectoryName(filePathName); if (System.IO.Directory.Exists(folder) == false) System.IO.Directory.CreateDirectory(folder); if (System.IO.File.Exists(filePathName) == true) System.IO.File.Delete(filePathName); System.IO.FileStream fs = new System.IO.FileStream(filePathName, System.IO.FileMode.Create, System.IO.FileAccess.Write); System.IO.BinaryWriter w = new System.IO.BinaryWriter(fs); try { w.Write(objData); } catch (Exception ex) { throw ex; } finally { w.Close(); fs.Close(); } return filePathName; } /// /// Http下载文件 /// public static string HttpDownloadFile(string url, string path) { // 设置参数 HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; //发送请求并获取相应回应数据 HttpWebResponse response = request.GetResponse() as HttpWebResponse; //直到request.GetResponse()程序才开始向目标网页发送Post请求 Stream responseStream = response.GetResponseStream(); //创建本地文件写入流 Stream stream = new FileStream(path, FileMode.Create); byte[] bArr = new byte[1024]; int size = responseStream.Read(bArr, 0, (int)bArr.Length); while (size > 0) { stream.Write(bArr, 0, size); size = responseStream.Read(bArr, 0, (int)bArr.Length); } stream.Close(); responseStream.Close(); return path; } /// /// 读取url获得数据. /// /// url /// 超时 /// 参数集合 /// 返回执行的内容 public static string ReadURLContext(string url, int timeOut) { return ReadURLContext(url, timeOut, Encoding.UTF8, null); } /// /// 读取URL内容 /// /// 要读取的url /// 超时时间 /// text code. /// 参数类型 /// 返回读取内容 public static string ReadURLContext(string url, int timeOut = 9999, Encoding encode = null, StringBuilder sb = null) { if (encode == null) encode = Encoding.UTF8; HttpWebRequest webRequest = null; try { webRequest = (HttpWebRequest)WebRequest.Create(url); webRequest.Method = "get"; webRequest.Timeout = timeOut; string str = webRequest.Address.AbsoluteUri; str = str.Substring(0, str.LastIndexOf("/")); } catch (Exception ex) { BP.DA.Log.DebugWriteError("@读取URL出现错误:URL=" + url + "@错误信息:" + ex.Message); return "err@读取URL出现错误:URL=" + url + "@错误信息:" + ex.Message; } // 因为它返回的实例类型是WebRequest而不是HttpWebRequest,因此记得要进行强制类型转换 // 接下来建立一个HttpWebResponse以便接收服务器发送的信息,它是调用HttpWebRequest.GetResponse来获取的: HttpWebResponse webResponse; try { webResponse = (HttpWebResponse)webRequest.GetResponse(); } catch (Exception ex) { try { // 如果出现死连接。 BP.DA.Log.DebugWriteError("@获取url=" + url + "失败。异常信息:" + ex.Message); return null; } catch { return ex.Message; } } //如果webResponse.StatusCode的值为HttpStatusCode.OK,表示成功,那你就可以接着读取接收到的内容了: // 获取接收到的流 Stream stream = webResponse.GetResponseStream(); System.IO.StreamReader streamReader = new StreamReader(stream, encode); string content = streamReader.ReadToEnd(); webResponse.Close(); return content; } /// /// 读取文件 /// /// 路径 /// 内容 public static string ReadTextFile(string file) { System.IO.StreamReader read = new System.IO.StreamReader(file, System.Text.Encoding.UTF8); // 文件流. string doc = read.ReadToEnd(); //读取完毕。 read.Close(); // 关闭。 return doc; } /// /// 读取Xml文件信息,并转换成DataSet对象 /// /// /// DataSet ds = new DataSet(); /// ds = CXmlFileToDataSet("/XML/upload.xml"); /// /// Xml文件地址 /// DataSet对象 public static DataSet CXmlFileToDataSet(string xmlFilePath) { if (!string.IsNullOrEmpty(xmlFilePath)) { //string path = HttpContext.Current.Server.MapPath(xmlFilePath); StringReader StrStream = null; XmlTextReader Xmlrdr = null; try { XmlDocument xmldoc = new XmlDocument(); //根据地址加载Xml文件 xmldoc.Load(xmlFilePath); DataSet ds = new DataSet(); //读取文件中的字符流 StrStream = new StringReader(xmldoc.InnerXml); //获取StrStream中的数据 Xmlrdr = new XmlTextReader(StrStream); //ds获取Xmlrdr中的数据 ds.ReadXml(Xmlrdr); return ds; } catch (Exception e) { throw e; } finally { //释放资源 if (Xmlrdr != null) { Xmlrdr.Close(); StrStream.Close(); StrStream.Dispose(); } } } else { return null; } } public static bool SaveAsFile(string filePath, string doc) { System.IO.StreamWriter sw = new System.IO.StreamWriter(filePath, false); sw.Write(doc); sw.Close(); return true; } public static string ReadTextFile2Html(string file) { return DataType.ParseText2Html(ReadTextFile(file)); } /// /// 判断是否全部是汉字 /// /// /// public static bool CheckIsChinese(string htmlstr) { char[] chs = htmlstr.ToCharArray(); foreach (char c in chs) { int i = c.ToString().Length; if (i == 1) return false; } return true; } #region 元角分 public static string TurnToFiels(float money) { string je = money.ToString("0.00"); string strs = ""; switch (je.Length) { case 7: // 千 百 十 元 角 分; strs = "D" + je.Substring(0, 1) + ".TW,THOU.TW,D" + je.Substring(1, 1) + ".TW,HUN.TW,D" + je.Substring(2, 1) + ".TW,TEN.TW,D" + je.Substring(3, 1) + ".TW,YUAN.TW,D" + je.Substring(5, 1) + ".TW,JIAO.TW,D" + je.Substring(6, 1) + ".TW,FEN.TW"; break; case 6: // 百; strs = "D" + je.Substring(0, 1) + ".TW,HUN.TW,D" + je.Substring(1, 1) + ".TW,TEN.TW,D" + je.Substring(2, 1) + ".TW,YUAN.TW,D" + je.Substring(4, 1) + ".TW,JIAO.TW,D" + je.Substring(5, 1) + ".TW,FEN.TW"; break; case 5: // 十; strs = "D" + je.Substring(0, 1) + ".TW,TEN.TW,D" + je.Substring(1, 1) + ".TW,YUAN.TW,D" + je.Substring(3, 1) + ".TW,JIAO.TW,D" + je.Substring(4, 1) + ".TW,FEN.TW"; break; case 4: // 元; if (money > 1) strs = "D" + je.Substring(0, 1) + ".TW,YUAN.TW,D" + je.Substring(2, 1) + ".TW,JIAO.TW,D" + je.Substring(3, 1) + ".TW,FEN.TW"; else strs = "D" + je.Substring(2, 1) + ".TW,JIAO.TW,D" + je.Substring(3, 1) + ".TW,FEN.TW"; break; default: throw new Exception("没有涉及到这么大的金额播出"); } // strs=strs.Replace(",D0.TW,JIAO.TW,D0.TW,FEN.TW",""); // 替换掉 .0角0分; // strs=strs.Replace("D0.TW,HUN.TW,D0.TW,TEN.TW","D0.TW"); // 替换掉 .0百0十 为 0 ; // strs=strs.Replace("D0.TW,THOU.TW","D0.TW"); // 替换掉零千。 // strs=strs.Replace("D0.TW,HUN.TW","D0.TW"); // strs=strs.Replace("D0.TW,TEN.TW","D0.TW"); // strs=strs.Replace("D0.TW,JIAO.TW","D0.TW"); // strs=strs.Replace("D0.TW,FEN.TW","D0.TW"); return strs; } #endregion public static string Html2Text(string htmlstr) { return System.Text.RegularExpressions.Regex.Replace(htmlstr, "<[^>]*>", ""); } public static string ByteToString(byte[] bye) { string s = ""; foreach (byte b in bye) { s += b.ToString(); } return s; } public static byte[] StringToByte(string s) { byte[] bs = new byte[s.Length]; char[] cs = s.ToCharArray(); int i = 0; foreach (char c in cs) { bs[i] = Convert.ToByte(c); i++; } return bs; } /// /// 取道百分比 /// /// /// /// public static string GetPercent(decimal a, decimal b) { decimal p = a / b; return p.ToString("0.00%"); } public static string GetWeek(int weekidx) { switch (weekidx) { case 0: return "星期日"; case 1: return "星期一"; case 2: return "星期二"; case 3: return "星期三"; case 4: return "星期四"; case 5: return "星期五"; case 6: return "星期六"; default: throw new Exception("error weekidx=" + weekidx); } } public static string GetABC(string abc) { switch (abc) { case "A": return "B"; case "B": return "C"; case "C": return "D"; case "D": return "E"; case "E": return "F"; case "F": return "G"; case "G": return "H"; case "H": return "I"; case "I": return "J"; case "J": return "K"; case "K": return "L"; case "L": return "M"; case "M": return "N"; case "N": return "O"; case "Z": return "A"; default: throw new Exception("abc error" + abc); } } public static string GetBig5(string text) { System.Text.Encoding e2312 = System.Text.Encoding.GetEncoding("GB2312"); byte[] bs = e2312.GetBytes(text); System.Text.Encoding e5 = System.Text.Encoding.GetEncoding("Big5"); byte[] bs5 = System.Text.Encoding.Convert(e2312, e5, bs); return e5.GetString(bs5); } /// /// 返回 data1 - data2 的天数. /// /// fromday /// today /// 相隔的天数 public static int SpanDays(string fromday, string today) { try { TimeSpan span = DateTime.Parse(today.Substring(0, 10)) - DateTime.Parse(fromday.Substring(0, 10)); return span.Days; } catch { //throw new Exception(ex.Message +"" +fromday +" " +today ) ; return 0; } } public static int SpanDays(string fromday, string today, bool isContHoliday) { DateTime fromDate = DateTime.Parse(fromday); DateTime toDate = DateTime.Parse(today); int day = 0; if (isContHoliday == false) { /* 设置节假日. */ while (fromDate.CompareTo(toDate) < 0) { if (BP.Sys.GloVar.Holidays.Contains(fromDate.ToString("MM-dd"))) { fromDate = fromDate.AddDays(1); continue; } day++; if (toDate.CompareTo(fromDate) == 0) break; fromDate = fromDate.AddDays(1); } } else { SpanDays(fromday, today); } return day; } public static int SpanHours(string fromday, string today) { var span = DateTime.Parse(today) - DateTime.Parse(fromday); var days = span.Days; return days; } /// /// 返回 QuarterFrom - QuarterTo 的季度. /// /// QuarterFrom /// QuarterTo /// 相隔的季度 public static int SpanQuarter(string _APFrom, string _APTo) { DateTime fromdate = Convert.ToDateTime(_APFrom + "-01"); DateTime todate = Convert.ToDateTime(_APTo + "-01"); int i = 0; if (fromdate > todate) throw new Exception("选择出错!起始时期" + _APFrom + "不能大于终止时期" + _APTo + "!"); while (fromdate <= todate) { i++; fromdate = fromdate.AddMonths(1); } int j = (i + 2) / 3; return j; } /// /// 到现在的天数。 /// /// /// public static int SpanDays(string data1) { TimeSpan span = DateTime.Now - DateTime.Parse(data1.Substring(0, 10)); return span.Days; } /// /// 检查是否是一个字段或者表名称 /// /// 要检查的字段或者表名称 /// 是否合法 public static bool CheckIsFieldOrTableName(string str) { string s = str.Substring(0, 1); if (DataType.IsNumStr(s)) return false; string chars = "~!@#$%^&*()_+`{}|:'<>?[];',./"; if (chars.Contains(s) == true) return false; return true; } public static string ParseText2Html(string val) { //val = val.Replace("&", "&"); //val = val.Replace("<","<"); //val = val.Replace(">",">"); //val = val.Replace(char(34), """); //val = val.Replace(char(9), "   "); //val = val.Replace(" ", " "); return val.Replace("\n", "
").Replace("~", "'"); //return val.Replace("\n", "
  ").Replace("~", "'"); } public static string ParseHtmlToText(string val) { if (val == null) return val; val = val.Replace(" ", " "); val = val.Replace(" ", " "); val = val.Replace("", ""); val = val.Replace("", ""); val = val.Replace("", ""); val = val.Replace("", ""); val = val.Replace("", ""); val = val.Replace("", ""); val = val.Replace("", ""); val = val.Replace("", ""); val = val.Replace("", ""); val = val.Replace("", ""); val = val.Replace("
", "\n\t"); val = val.Replace("
", "\n\t"); val = val.Replace(" ", " "); val = val.Replace("



", "

"); val = val.Replace("



", "

"); val = val.Replace("

", "
"); char[] chs = val.ToCharArray(); bool isStartRec = false; string recStr = ""; foreach (char c in chs) { if (c == '<') { recStr = ""; isStartRec = true; /* 开始记录 */ } if (isStartRec) { recStr += c.ToString(); } if (c == '>') { isStartRec = false; if (recStr == "") { isStartRec = false; continue; } /* 开始分析这个标记内的东西。*/ string market = recStr.ToLower(); if (market.Contains(" /// 将文本转换成可用做Name,Text的文本,文本中仅允许含有汉字、字母、数字、下划线 /// /// 待转换的文本 /// 文本最大长度,0为不限制,超过maxLen,截取前maxLen字符长度 /// public static string ParseStringForName(string nameStr, int maxLen) { if (string.IsNullOrWhiteSpace(nameStr)) return string.Empty; string nStr = Regex.Replace(nameStr, RegEx_Replace_OnlyHSZX, ""); if (maxLen > 0 && nStr.Length > maxLen) return nStr.Substring(0, maxLen); return nStr; } /// /// 将文本转换成可用做No的文本,文本中仅允许含有字母、数字、下划线,且开头只能是字母 /// /// 待转换的文本 /// 文本最大长度,0为不限制,超过maxLen,截取前maxLen字符长度 /// public static string ParseStringForNo(string noStr, int maxLen) { if (string.IsNullOrWhiteSpace(noStr)) return string.Empty; string nStr = Regex.Replace(Regex.Replace(noStr, RegEx_Replace_OnlySZX, ""), RegEx_Replace_FirstXZ, ""); if (maxLen > 0 && nStr.Length > maxLen) return nStr.Substring(0, maxLen); return nStr; } /// /// 去除指定字符串中非数字的字符 /// /// 字符串 /// public static string ParseStringOnlyIntNumber(string str) { if (string.IsNullOrWhiteSpace(str)) return string.Empty; return Regex.Replace(str, RegEx_Replace_OnlyIntNum, ""); } /// /// 去除指定字符串中危险字符 /// 注:含有这些字符的参数经过拼接,组成SQL可能包含危险语句 /// 涉及字符:' ; -- / & > < /// /// 字符串 /// public static string ParseStringFilterDangerousSymbols(string str) { if (string.IsNullOrWhiteSpace(str)) return string.Empty; return Regex.Replace(str, RegEx_Replace_FilterDangerousSymbols, "").Replace("<", "<").Replace(">", ">").Replace("&", "&"); } public static string DealFromatSQLWhereIn(string ids) { if (ids.Contains("'") == true) return ids; string[] strs = ids.Split(','); string sqlIn = ""; foreach (string str in strs) { sqlIn += ",'" + str + "'"; } return sqlIn.Substring(1); } /// /// 将中文转化成拼音 /// /// /// public static string ParseStringToPinyin(string exp) { #region 特殊字符处理. switch (exp) { case "电话": return "Tel"; case "地址": return "Addr"; case "年龄": return "Age"; case "邮件": return "Email"; case "单价": return "DanJia"; case "金额": return "JinE"; case "单据编号": return "BillNo"; default: break; } #endregion 特殊字符处理. //特殊处理. exp = exp.Replace("单价", "DanJia"); exp = exp.Replace("单件", "DanJian"); exp = exp.Replace("单个", "DanGe"); exp = exp.Trim(); string pinYin = "", str = null; char[] chars = exp.ToCharArray(); foreach (char c in chars) { try { str = CCFormAPI.ChinaMulTonesToPinYin(c.ToString()); if (str == null) { str = BP.Tools.chs2py.convert(c.ToString()); } pinYin += str.Substring(0, 1).ToUpper() + str.Substring(1); } catch { pinYin += c; } } return pinYin; } /// /// 转化成拼音第一个字母大字 /// /// 要转化的中文串 /// 拼音 public static string ParseStringToPinyinWordFirst(string str) { try { String _Temp = ""; for (int i = 0; i < str.Length; i++) { _Temp = _Temp + DataType.ParseStringToPinyin(str.Substring(i, 1)); } return _Temp; } catch (Exception ex) { throw new Exception("@错误:" + str + ",不能转换成拼音。"); } } /// /// 转化成拼音第一个字母大字 /// /// 要转化的中文串 /// 拼音 public static string ParseStringToPinyinJianXie(string str) { try { String _Temp = null; var re = string.Empty; for (int i = 0; i < str.Length; i++) { re = DataType.ParseStringToPinyin(str.Substring(i, 1)); _Temp += re.Length == 0 ? "" : re.Substring(0, 1); } return _Temp; } catch (Exception ex) { throw new Exception("@错误:" + str + ",不能转换成拼音。"); } } /// /// 转化成 decimal /// /// /// public static decimal ParseExpToDecimal(string exp) { if (exp.Trim() == "") throw new Exception("DataType.ParseExpToDecimal要转换的表达式为空。"); exp = exp.Replace("+-", "-"); exp = exp.Replace("¥", ""); //exp=exp.Replace(" ",""); 不能替换,因为有sql表达公式时间,会出现错误。 exp = exp.Replace("\n", ""); exp = exp.Replace("\t", ""); exp = exp.Replace("+", "+"); exp = exp.Replace("-", "-"); exp = exp.Replace("*", "*"); exp = exp.Replace("/", "/"); exp = exp.Replace(")", ")"); exp = exp.Replace("(", "("); exp = exp.Replace(".00.00", "00"); exp = exp.Replace("--", "- -"); if (exp.IndexOf("@") != -1) return 0; string val = exp.Substring(0, 1); if (val == "-") exp = exp.Substring(1); // exp = exp.Replace("*100%", "*100"); exp = exp.Replace("*100%", "*1"); try { return decimal.Parse(exp); } catch { } try { string sql = "SELECT " + exp + " as Num "; switch (BP.Difference.SystemConfig.AppCenterDBType) { case DBType.MSSQL: case DBType.Access: sql = "SELECT " + exp + " as Num "; return DBAccess.RunSQLReturnValDecimal(sql, 0, 2); case DBType.Oracle: case DBType.KingBaseR3: case DBType.KingBaseR6: sql = "SELECT " + exp + " NUM from DUAL "; return DBAccess.RunSQLReturnValDecimal(sql, 0, 2); case DBType.Informix: sql = "SELECT " + exp + " NUM from taa_onerow "; return DBAccess.RunSQLReturnValDecimal(sql, 0, 2); default: break; } } catch (Exception ex) { BP.DA.Log.DebugWriteError(ex.Message); /* 如果抛出异常就按 0 计算。 */ return 0; } exp = exp.Replace("-0", ""); try { BP.Tools.StringExpressionCalculate sc = new BP.Tools.StringExpressionCalculate(); return sc.TurnToDecimal(exp); } catch (Exception ex) { if (exp.IndexOf("/") != -1) return 0; throw new Exception("表达式(\"" + exp + "\")计算错误:" + ex.Message); } } public static string ParseFloatToCash(float money) { if (money == 0) return "零圆零角零分"; BP.Tools.DealString d = new BP.Tools.DealString(); d.InputString = money.ToString(); d.ConvertToChineseNum(); return d.OutString; } public static string ParseFloatToRMB(float money) { if (money == 0) return "零圆零角零分"; BP.Tools.DealString d = new BP.Tools.DealString(); d.InputString = money.ToString(); d.ConvertToChineseNum(); return d.OutString; } /// /// 得到一个日期,根据系统 /// /// /// public DateTime Parse(string dataStr) { return DateTime.Parse(dataStr); } /// /// 系统定义的时间格式 yyyy-MM-dd . /// public static string SysDataFormat { get { return "yyyy-MM-dd"; } } #region 与周相关. /// /// 当前周次 /// public static int CurrentWeek { get { System.Globalization.GregorianCalendar gc = new System.Globalization.GregorianCalendar(); int weekOfYear = gc.GetWeekOfYear(DateTime.Now, System.Globalization.CalendarWeekRule.FirstDay, DayOfWeek.Monday); return weekOfYear; } } /// /// 根据一个日期,获得该日期属于一年的第几周. /// /// 日期时间串,要符合bp格式. /// 该日期属于所在年度的第几周 public static int CurrentWeekGetWeekByDay(string dataTimeStr) { System.Globalization.GregorianCalendar gc = new System.Globalization.GregorianCalendar(); int weekOfYear = gc.GetWeekOfYear(DataType.ParseSysDate2DateTime(dataTimeStr), System.Globalization.CalendarWeekRule.FirstDay, DayOfWeek.Monday); return weekOfYear; } #endregion /// /// 格式化日期类型 /// /// 日期字符串 /// 标准的日期类型 public static string FormatDateTime(string dataStr) { return dataStr; } public static string CurrentDateByFormart(string dataFormat) { return DateTime.Now.ToString(dataFormat); } /// /// 当前的日期 /// public static string CurrentDate { get { return DateTime.Now.ToString(DataType.SysDataFormat); } } public static string CurrentDateTime { get { return DateTime.Now.ToString(DataType.SysDatatimeFormat); } } public static string CurrentTime { get { return DateTime.Now.ToString("hh:mm"); } } /// /// /// public static string CurrentTimeQuarter { get { return DateTime.Now.ToString("hh:mm"); } } /// /// 给一个时间,返回一个刻种时间。 /// /// /// public static string ParseTime2TimeQuarter(string time) { string hh = time.Substring(0, 3); int mm = int.Parse(time.Substring(3, 2)); if (mm == 0) { return hh + "00"; } if (mm < 15) { return hh + "00"; } if (mm >= 15 && mm < 30) { return hh + "15"; } if (mm >= 30 && mm < 45) { return hh + "30"; } if (mm >= 45 && mm < 60) { return hh + "45"; } return time; } public static string CurrentDay { get { return DateTime.Now.ToString("dd"); } } /// /// 当前的会计期间 /// public static string CurrentAP { get { return DateTime.Now.ToString("yyyy-MM"); } } public static string Keys { get { return "Rels,DESC,TABLE,ALERT,"; } } /// /// 当前的会计期间 /// public static string CurrentYear { get { return DateTime.Now.ToString("yyyy"); } } public static string CurrentMonth { get { return DateTime.Now.ToString("MM"); } } /// /// 当前的会计期间 yyyy-MM /// public static string CurrentYearMonth { get { return DateTime.Now.ToString("yyyy-MM"); } } public static string GetJDByMM(string mm) { string jd = "01"; switch (mm) { case "01": case "02": case "03": jd = "01"; break; case "04": case "05": case "06": jd = "04"; break; case "07": case "08": case "09": jd = "07"; break; case "10": case "11": case "12": jd = "10"; break; default: throw new Exception("@不是有效的月份格式" + mm); } return jd; } /// /// 当前的季度期间yyyy-MM /// public static string CurrentAPOfJD { get { return DateTime.Now.ToString("yyyy") + "-" + DataType.GetJDByMM(DateTime.Now.ToString("MM")); } } /// /// 当前的季度的前一个季度. /// public static string CurrentAPOfJDOfFrontFamily { get { DateTime now = DateTime.Now.AddMonths(-3); return now.ToString("yyyy") + "-" + DataType.GetJDByMM(now.ToString("MM")); } } /// /// yyyy-JD /// public static string CurrentAPOfPrevious { get { int m = int.Parse(DateTime.Now.ToString("MM")); return DateTime.Now.ToString("yyyy-MM"); } } /// /// 取出当前月份的上一个月份 /// public static string CurrentNYOfPrevious { get { DateTime dt = DateTime.Now; dt = dt.AddMonths(-1); return dt.ToString("yyyy-MM"); } } /// /// 取出当前月份的上上一个月份 /// public static string ShangCurrentNYOfPrevious { get { DateTime dt = DateTime.Now; dt = dt.AddMonths(-2); return dt.ToString("yyyy-MM"); } } /// /// 当前的季度期间 /// public static string CurrentAPOfYear { get { return DateTime.Now.ToString("yyyy"); } } public static string CurrentDateTimeOfDef { get { switch (BP.Web.WebUser.SysLang) { case "CH": case "B5": return CurrentDateTimeCNOfShort; case "EN": return DateTime.Now.ToString("MM/DD/YYYY"); default: break; } return CurrentDateTimeCNOfShort; } } public static string CurrentDateTimeCNOfShort { get { return DateTime.Now.ToString("yy年MM月dd日 HH时mm分"); } } public static string CurrentDateTimeCNOfLong { get { return DateTime.Now.ToString("yy年MM月dd日 HH时mm分ss秒"); } } public static string CurrentDateCNOfShort { get { return DateTime.Now.ToString("yy年MM月dd日"); } } public static string CurrentDateCNOfLong { get { return DateTime.Now.ToString("yyyy年MM月dd日"); } } /// /// 当前的日期时间 /// public static string CurrentDateTimeCN { get { return DateTime.Now.ToString(DataType.SysDataFormatCN) + "," + GetWeekName(DateTime.Now.DayOfWeek); } } private static string GetWeekName(System.DayOfWeek dw) { switch (dw) { case DayOfWeek.Monday: return "星期一"; case DayOfWeek.Thursday: return "星期四"; case DayOfWeek.Friday: return "星期五"; case DayOfWeek.Saturday: return "星期六"; case DayOfWeek.Sunday: return "星期日"; case DayOfWeek.Tuesday: return "星期二"; case DayOfWeek.Wednesday: return "星期三"; default: return ""; } } /// /// 当前的日期时间 /// public static string CurrentDateTimess { get { return DateTime.Now.ToString(DataType.SysDateTimeFormat + ":ss"); } } /// /// 把chichengsoft本系统日期格式转换为系统日期格式。 /// /// yyyy-MM-dd /// DateTime public static DateTime ParseSysDate2DateTime(string sysDateformat) { if (sysDateformat == null || sysDateformat.Trim().Length == 0) return DateTime.Now; try { if (sysDateformat.Length > 10) return ParseSysDateTime2DateTime(sysDateformat); sysDateformat = sysDateformat.Trim(); //DateTime.Parse(sysDateformat, string[] strs = null; if (sysDateformat.IndexOf("-") != -1) { strs = sysDateformat.Split('-'); } if (sysDateformat.IndexOf("/") != -1) { strs = sysDateformat.Split('/'); } int year = int.Parse(strs[0]); int month = int.Parse(strs[1]); int day = int.Parse(strs[2]); //DateTime dt= DateTime.Now; return new DateTime(year, month, day, 0, 0, 0); } catch (Exception ex) { throw new Exception("日期[" + sysDateformat + "]转换出现错误:" + ex.Message + "无效的日期是格式。"); } //return dt; } /// /// 2005-11-04 09:12 /// /// 2005-11-04 09:12 /// public static DateTime ParseSysDateTime2DateTime(string sysDateformat) { try { return Convert.ToDateTime(sysDateformat); } catch (Exception ex) { throw new Exception("@时间格式不正确:" + sysDateformat + "@技术信息:" + ex.Message); } } /// /// 获取两个时间之间的字符串表示形式,如:1天2时34分 /// added by liuxc,2014-12-4 /// /// 开始时间 /// 结束时间 /// 返回:x天x时x分 public static string GetSpanTime(DateTime t1, DateTime t2) { var span = t2 - t1; var days = span.Days; var hours = span.Hours; var minutes = span.Minutes; if (days == 0 && hours == 0 && minutes == 0) minutes = span.Seconds > 0 ? 1 : 0; var spanStr = string.Empty; if (days > 0) spanStr += days + "天"; if (hours > 0) spanStr += hours + "时"; if (minutes > 0) spanStr += minutes + "分"; if (spanStr.Length == 0) spanStr = "0分"; return spanStr; } /// /// 获得两个日期之间的天数 /// /// /// /// public static float GeTimeLimits(string dtoffrom, string dtofto) { if (dtoffrom == null || dtoffrom.Length <= 7) return 0; if (dtofto == null || dtofto.Length <= 7) return 0; DateTime dtfrom = DataType.ParseSysDate2DateTime(dtoffrom); DateTime dtto = DataType.ParseSysDate2DateTime(dtofto); TimeSpan ts = dtto - dtfrom; return (float)Math.Round(ts.TotalDays, 2); } /// /// 获得两个时间的参数 /// /// 时间从 /// public static float GeTimeLimits(string dtoffrom) { return GeTimeLimits(dtoffrom, DataType.CurrentDateTime); } public static float GetSpanMinute(string fromdatetim, string toDateTime) { DateTime dtfrom = DataType.ParseSysDateTime2DateTime(fromdatetim); DateTime dtto = DataType.ParseSysDateTime2DateTime(toDateTime); TimeSpan ts = dtfrom - dtto; return (float)ts.TotalMinutes; } /// /// 到现在的时间 /// /// /// 分中数 public static int GetSpanMinute(string fromdatetim) { DateTime dtfrom = DataType.ParseSysDateTime2DateTime(fromdatetim); DateTime dtto = DateTime.Now; TimeSpan ts = dtfrom - dtto; return (int)ts.TotalMinutes + ts.Hours * 60; } /// /// 系统定义日期时间格式 yyyy-MM-dd hh:mm /// public static string SysDateTimeFormat { get { return "yyyy-MM-dd HH:mm"; } } public static string SysDataFormatCN { get { return "yyyy年MM月dd日"; } } public static string SysDatatimeFormat { get { return "yyyy-MM-dd HH:mm"; } } public static string SysDatatimeFormatCN { get { return "yyyy年MM月dd日 HH时mm分"; } } public static DBUrlType GetDBUrlByString(string strDBUrl) { switch (strDBUrl) { case "AppCenterDSN": return DBUrlType.AppCenterDSN; default: throw new Exception("@没有此类型[" + strDBUrl + "]"); } } public static int GetDataTypeByString(string datatype) { switch (datatype) { case "AppBoolean": return DataType.AppBoolean; case "AppDate": return DataType.AppDate; case "AppDateTime": return DataType.AppDateTime; case "AppDouble": return DataType.AppDouble; case "AppFloat": return DataType.AppFloat; case "AppInt": return DataType.AppInt; case "AppMoney": return DataType.AppMoney; case "AppString": return DataType.AppString; default: throw new Exception("@没有此类型" + datatype); } } public static string GetDataTypeDese(int datatype) { //if (BP.Web.WebUser.SysLang == "CH") //{ // switch (datatype) // { // case DataType.AppBoolean: // return "布尔(Int)"; // case DataType.AppDate: // return "日期nvarchar"; // case DataType.AppDateTime: // return "日期时间nvarchar"; // case DataType.AppDouble: // return "双精度(double)"; // case DataType.AppFloat: // return "浮点(float)"; // case DataType.AppInt: // return "整型(int)"; // case DataType.AppMoney: // return "货币(float)"; // case DataType.AppString: // return "字符(nvarchar)"; // default: // throw new Exception("@没有此类型"); // } //} switch (datatype) { case DataType.AppBoolean: return "Boolen"; case DataType.AppDate: return "Date"; case DataType.AppDateTime: return "Datetime"; case DataType.AppDouble: return "Double"; case DataType.AppFloat: return "Float"; case DataType.AppInt: return "Int"; case DataType.AppMoney: return "Money"; case DataType.AppString: return "varchar"; default: throw new Exception("@没有此类型"); } } /// /// 产生适应的图片大小 /// 用途:在固定容器大小的位置,显示固定的图片。 /// /// 容器高度 /// 容器宽度 /// 原始图片高度 /// 原始图片宽度 /// 是否填充:是,小图片将会放大填充容器. 否,小图片不放大保留原来的大小 public static void GenerPictSize(float panelHeight, float panelWidth, ref float AdaptHeight, ref float AdaptWidth, bool isFullPanel) { if (isFullPanel == false) { if (panelHeight <= AdaptHeight && panelWidth <= AdaptWidth) return; } float zoom = 1; zoom = System.Math.Min(panelHeight / AdaptHeight, panelWidth / AdaptWidth); AdaptHeight = AdaptHeight * zoom; AdaptWidth = AdaptWidth * zoom; } #region 正则表达式 /// /// (RegEx.Replace操作使用)仅含有汉字、数字、字母、下划线 /// 示例: /// Console.WriteLine(RegEx.Replace("姓名@-._#::“|:$?>a:12",RegEx_Replace_OnlyHSZX,"")); /// 输出:姓名_a12 /// public const string RegEx_Replace_OnlyHSZX = @"[^0-9a-zA-Z_\u4e00-\u9fa5]"; /// /// (RegEx.Replace操作使用)仅含有数字、字母、下划线 /// 示例: /// Console.WriteLine(RegEx.Replace("姓名@-._#::“|:$?>a:12",RegEx_Replace_OnlySZX,"")); /// 输出:_a12 /// public const string RegEx_Replace_OnlySZX = @"[\u4e00-\u9fa5]|[^0-9a-zA-Z_]"; /// /// (RegEx.Replace操作使用)字符串开头不能为数字或下划线 /// 示例: /// Console.WriteLine(RegEx.Replace("_12_a1",RegEx_Replace_FirstXZ,"")); /// 输出:a1 /// public const string RegEx_Replace_FirstXZ = "^(_|[0-9])+"; /// /// (RegEx.Replace操作使用)仅含有整形数字 /// 示例: /// Console.WriteLine(RegEx.Replace("_12_a1",RegEx_Replace_OnlyIntNum,"")); /// 输出:121 /// public const string RegEx_Replace_OnlyIntNum = "[^0-9]"; /// /// (RegEx.Replace操作使用)字符串不能含有指定危险字符 /// 示例: /// Console.WriteLine(RegEx.Replace("'_1--2/_a1",RegEx_Replace_FilterDangerousSymbols,"")); /// 输出:_12_a1 /// public const string RegEx_Replace_FilterDangerousSymbols = "[';/]|[-]{2}"; #endregion #region 数据类型。 /// /// string /// public const int AppString = 1; /// /// int /// public const int AppInt = 2; /// /// float /// public const int AppFloat = 3; /// /// AppBoolean /// public const int AppBoolean = 4; /// /// AppDouble /// public const int AppDouble = 5; /// /// AppDate /// public const int AppDate = 6; /// /// AppDateTime /// public const int AppDateTime = 7; /// /// AppMoney /// public const int AppMoney = 8; #endregion #region 其他方法. public static string StringToDateStr(string str) { try { DateTime dt = DateTime.Parse(str); string year = dt.Year.ToString(); string month = dt.Month.ToString(); string day = dt.Day.ToString(); return year + "-" + month.PadLeft(2, '0') + "-" + day.PadLeft(2, '0'); //return str; } catch (System.Exception ex) { throw ex; } } public static string GenerSpace(int spaceNum) { if (spaceNum <= 0) return ""; string strs = ""; while (spaceNum != 0) { strs += "  "; spaceNum--; } return strs; } /// /// 根据序号生成Idx 的ABC /// /// /// public static string GenerABC(int idx) { string strs = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; char[] mystrs = strs.ToCharArray(); return mystrs[idx].ToString(); } public static string GenerBR(int spaceNum) { string strs = ""; while (spaceNum != 0) { strs += "
"; spaceNum--; } return strs; } public static bool IsImgExt(string ext) { ext = ext.Replace(".", "").ToLower(); switch (ext) { case "gif": case "jpg": case "jepg": case "jpeg": case "bmp": case "png": case "tif": case "gsp": case "mov": case "psd": case "tiff": case "wmf": return true; default: return false; } } public static bool IsVoideExt(string ext) { ext = ext.Replace(".", "").ToLower(); switch (ext) { case "mp3": case "mp4": case "asf": case "wma": case "rm": case "rmvb": case "mpg": case "wmv": case "quicktime": case "avi": case "flv": case "mpeg": return true; default: return false; } } public static bool IsMobile(string input) { if (input.Length == 11 && input.Substring(0, 1).Equals("1")) return true; if (input.Length < 11) return false; //电信手机号码正则 string dianxin = @"^1[3578][01379]\d{8}$"; Regex regexDX = new Regex(dianxin); //联通手机号码正则 string liantong = @"^1[34578][01256]\d{8}"; Regex regexLT = new Regex(dianxin); //移动手机号码正则 string yidong = @"^(1[012345678]\d{8}|1[345678][012356789]\d{8})$"; Regex regexYD = new Regex(dianxin); if (regexDX.IsMatch(input) || regexLT.IsMatch(input) || regexYD.IsMatch(input)) return true; return false; } /// /// 判断是否是数值类型 /// /// /// public static bool IsNumStr(string value) { if (value == null || "".Equals(value)) { return false; } return Regex.IsMatch(value, @"^[+-]?\d*[.]?\d*$"); } ///// ///// 判断是否是Num 字串。 ///// ///// ///// //public static bool IsNumStr(string str) //{ // try // { // decimal d = decimal.Parse(str); // return true; // } // catch // { // return false; // } //} /// /// 是不时奇数 /// /// will judg value /// public static bool IsQS(int num) { int ii = 0; for (int i = 0; i < 500; i++) { if (num == ii) return false; ii = ii + 2; } return true; } public static bool StringToBoolean(string str) { if (str == null || str == "" || str == ",nbsp;") return false; if (str == "0" || str == "1") { if (str == "0") return false; else return true; } else if (str == "true" || str == "false") { if (str == "false") return false; else return true; } else if (str == "是" || str == "否") { if (str == "否") return false; else return true; } else throw new Exception("@要转换的[" + str + "]不是bool 类型"); } #endregion 其他方法. #region 与门户相关的. #if DEBUG static TimeSpan ts = new TimeSpan(0, 10, 0); #else static TimeSpan ts = new TimeSpan(0, 1, 0); #endif private static string _BPMHost = null; /// /// 当前BPMHost /// public static string BPMHost { get { if (_BPMHost != null) return _BPMHost; _BPMHost = "http://" + HttpContextHelper.RequestUrlAuthority; return _BPMHost; } } #endregion 与门户相关的. } }