服务端相关代码也合并到仓库

This commit is contained in:
wule committed 2025-07-14 19:08:12 +08:00
1 parent fef54e1f0f
commit 879b72e21a
32 files changed
+3626 -1

No files matched your search

@@ -0,0 +1,60 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Web;
namespace KJD_Web.Utils
{
public class EncrypUtil
{
/// <summary>
/// 加密算法
/// </summary>
/// <param name="s">加密字符串</param>
/// <returns></returns>
public static string Encryption(int s)
{
string sign = $"{s}sdhewu*/fhAAue48485ew5+5%@3485esGFFHFD";
return GetMd5(sign);
}
/// <summary>
/// MD5加密
/// </summary>
/// <param name="instring"></param>
/// <returns></returns>
public static string GetMd5(string instring)
{
byte[] result = Encoding.Default.GetBytes(instring.Trim());
MD5 md5 = new MD5CryptoServiceProvider();
byte[] output = md5.ComputeHash(result);
return BitConverter.ToString(output).Replace("-", "");
}
/// <summary>
/// 获取文件MD5值
/// </summary>
/// <param name="FilePath"></param>
/// <returns></returns>
public static string GetFileMd5(string FilePath)
{
try
{
FileStream get_file = new FileStream(FilePath, FileMode.Open, FileAccess.Read, FileShare.Read);
System.Security.Cryptography.MD5CryptoServiceProvider get_md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
byte[] hash_byte = get_md5.ComputeHash(get_file);
string resule = System.BitConverter.ToString(hash_byte);
resule = resule.Replace("-", "");
get_file.Close();
return resule;
}
catch (Exception e)
{
return e.ToString();
}
}
}
}
@@ -0,0 +1,153 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Net;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Web;
namespace KJD_Web.Utils
{
public class HtmlUtils
{
static public string UrlDecodeUtf8(string value)
{
if (value == null)
{
return null;
}
Encoding encoding = Encoding.UTF8;//你的编码 也可能是GBK
int length = value.Length;
UrlDecoder decoder = new UrlDecoder(length, encoding);
for (int i = 0; i < length; i++)
{
char ch = value[i];
if (ch == '+')
{
ch = ' ';
}
else if ((ch == '%') && (i < (length - 2)))
{
if ((value[i + 1] == 'u') && (i < (length - 5)))
{
int num3 = HexToInt(value[i + 2]);
int num4 = HexToInt(value[i + 3]);
int num5 = HexToInt(value[i + 4]);
int num6 = HexToInt(value[i + 5]);
if (((num3 < 0) || (num4 < 0)) || ((num5 < 0) || (num6 < 0)))
{
goto Label_010B;
}
ch = (char)((((num3 << 12) | (num4 << 8)) | (num5 << 4)) | num6);
i += 5;
decoder.AddChar(ch);
continue;
}
int num7 = HexToInt(value[i + 1]);
int num8 = HexToInt(value[i + 2]);
if ((num7 >= 0) && (num8 >= 0))
{
byte b = (byte)((num7 << 4) | num8);
i += 2;
decoder.AddByte(b);
continue;
}
}
Label_010B:
if ((ch & 0xff80) == 0)
{
decoder.AddByte((byte)ch);
}
else
{
decoder.AddChar(ch);
}
}
return decoder.GetString();
}
public static int HexToInt(char h)
{
if ((h >= '0') && (h <= '9'))
{
return (h - '0');
}
if ((h >= 'a') && (h <= 'f'))
{
return ((h - 'a') + 10);
}
if ((h >= 'A') && (h <= 'F'))
{
return ((h - 'A') + 10);
}
return -1;
}
}
/// <summary>
/// class UrlDecoder
/// </summary>
class UrlDecoder
{
// Fields
private int _bufferSize;
private byte[] _byteBuffer;
private char[] _charBuffer;
private Encoding _encoding;
private int _numBytes;
private int _numChars;
// Methods
internal UrlDecoder(int bufferSize, Encoding encoding)
{
this._bufferSize = bufferSize;
this._encoding = encoding;
this._charBuffer = new char[bufferSize];
}
internal void AddByte(byte b)
{
if (this._byteBuffer == null)
{
this._byteBuffer = new byte[this._bufferSize];
}
this._byteBuffer[this._numBytes++] = b;
}
internal void AddChar(char ch)
{
if (this._numBytes > 0)
{
this.FlushBytes();
}
this._charBuffer[this._numChars++] = ch;
}
private void FlushBytes()
{
if (this._numBytes > 0)
{
this._numChars += this._encoding.GetChars(this._byteBuffer, 0, this._numBytes, this._charBuffer, this._numChars);
this._numBytes = 0;
}
}
internal string GetString()
{
if (this._numBytes > 0)
{
this.FlushBytes();
}
if (this._numChars > 0)
{
return new string(this._charBuffer, 0, this._numChars);
}
return string.Empty;
}
}
}
@@ -0,0 +1,47 @@
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
namespace KJD_Web.Utils
{
public class JsonUtils
{
/// <summary>
/// 反序列化Json字符串生成对象实体
/// </summary>
/// <typeparam name="T">对象类型</typeparam>
/// <param name="jsonStr">json字符串</param>
/// <returns>对象实体</returns>
public static T DeserializeJsonToObject<T>(string jsonStr) where T : class
{
try
{
JsonSerializer serializer = new JsonSerializer();
StringReader sr = new StringReader(jsonStr);
object obj = serializer.Deserialize(new JsonTextReader(sr), typeof(T));
T t = obj as T;
return t;
}
catch
{
return null;
}
}
public static string SerializerObjectToString(object obj)
{
try
{
string str = JsonConvert.SerializeObject(obj, Formatting.None);
return str;
}
catch
{
return null;
}
}
}
}
@@ -0,0 +1,682 @@
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Threading;
using System.Web;
namespace KJD_Web.Utils
{
public class MysqlUtils
{
public string Message = "";
/// <summary>
/// 数据库连接字符串
/// </summary>
private string ConnString = "";
/// <summary>
/// 数据库连接
/// </summary>
private MySqlConnection Conn;
/// <summary>
/// 数据库读取对象
/// </summary>
private MySqlDataReader reader;
/// <summary>
/// 数据库执行对象
/// </summary>
private MySqlCommand cmd = new MySqlCommand();
/// <summary>
/// 错误信息
/// </summary>
//public static string ErrorString = "";
/// <summary>
/// 超时(秒)
/// </summary>
public int TimeOut = 120;
/// <summary>
/// 链接状态
/// </summary>
public bool Connected
{
get { return Conn != null && Conn.State == ConnectionState.Open; }
}
/// <summary>
/// 是否正在执行
/// </summary>
public bool IsRunning = false;
/// <summary>
/// 初始化数据库链接
/// </summary>
/// <param name="connString">数据库链接</param>
public MysqlUtils(string connString)
{
ConnString = connString;
ConnTo();
}
/// <summary>
/// 去掉SQL中的特殊字符
/// </summary>
/// <param name="value">字符串</param>
/// <returns></returns>
public string ReplaceSql(string value)
{
return ReplaceSqlSpecial(value);
}
/// <summary>
/// 反转字符串,用于mysql反向索引
/// </summary>
/// <param name="temp"></param>
/// <returns></returns>
public static string ReverseString(string temp)
{
if (string.IsNullOrEmpty(temp))
return null;
char[] l = temp.ToCharArray();
Array.Reverse(l);
return new string(l);
}
/// <summary>
/// 去掉SQL中的特殊字符
/// </summary>
/// <param name="value">字符串</param>
/// <returns></returns>
public static string ReplaceSqlSpecial(string value)
{
if (string.IsNullOrEmpty(value))
return null;
value = value.Replace("\\", "\\\\");
value = value.Replace("'", "''");
//value = value.Replace("\"", "\\\"");
return value;
}
/// <summary>
/// 插入数据
/// </summary>
/// <param name="table"></param>
/// <param name="keys"></param>
/// <returns></returns>
public int Insert(string table, List<MysqlKeyValue> keys)
{
string temp = "", tempx = "";
for (int i = 0; i < keys.Count; i++)
{
temp += ",`" + keys[i].Key + "`";
tempx += ",'" + keys[i].Value + "'";
}
temp = temp.Substring(1);
tempx = tempx.Substring(1);
string sql = "insert into " + table + " (" + temp + ") values (" + tempx + ") ";
return (int)ExecuteInsertId(sql);
}
/// <summary>
/// 返回执行表
/// </summary>
/// <param name="SqlString"></param>
/// <returns></returns>
public DataTable ExecuteDataTable(string SqlString)
{
return ExecuteDataTable(SqlString, null);
}
/// <summary>
/// 执行sql返回DataTable
/// </summary>
/// <param name="SqlString">SQL语句</param>
/// <param name="parms">Sql参数</param>
/// <returns>DataTable</returns>
public DataTable ExecuteDataTable(string SqlString, MySqlParameter[] parms)
{
SleepOrGo();
bool frist = true;
Retry:
if (Conn == null || Conn.State != ConnectionState.Open)
ConnTo();
try
{
CmdIni();
cmd.CommandText = SqlString;
if (parms != null)
foreach (MySqlParameter pram in parms)
cmd.Parameters.Add(pram);
DataSet ds = new DataSet();
MySqlDataAdapter adapter = new MySqlDataAdapter();
adapter.SelectCommand = cmd;
adapter.Fill(ds);
return ds.Tables[0];
//DataTable dt = new DataTable();
//try
//{
// reader = cmd.ExecuteReader();
// dt.Load(reader);
//}
//catch
//{
// reader = cmd.ExecuteReader();
// dt = Read(ref reader);
//}
//return dt;
}
catch (Exception e)
{
if (frist)
{
frist = false;
ErrorDoing(e.Message);
goto Retry;
}
AddError(e.Message, SqlString);
return null;
}
finally
{
CloseReader();
IsRunning = false;
}
}
/// <summary>
/// 针对不同错误,执行不同的修正
/// </summary>
/// <param name="message"></param>
private void ErrorDoing(string message)
{
Message = message;
if (string.IsNullOrEmpty(message))
return;
if (message.Contains("Incorrect string value"))
return;
if (message.Contains("Connection must be valid and open"))
ConnTo();
if (message.Contains("There is already an open DataReader"))
{
Thread.Sleep(500);
ConnTo();
}
if (message.Contains("Fatal error encountered during command execution."))
ConnTo();
if (message.Contains(" StreamWriter ") || message.Contains("未将对象引用设置到对象的实例") || message.Contains("未将对象"))
ConnTo();
CloseReader();
Random ra = new Random(Guid.NewGuid().GetHashCode());
Thread.Sleep(ra.Next(200, 2000));
}
/// <summary>
/// 关闭读取线程
/// </summary>
private void CloseReader()
{
try
{
if (reader != null && !reader.IsClosed)
reader.Close();
cmd.Dispose();
//reader = null;
}
catch
{
}
}
/// <summary>
/// 返回执行行
/// </summary>
/// <param name="SqlString"></param>
/// <returns></returns>
public DataRow ExecuteDataTableRow(string SqlString)
{
return ExecuteDataTableRow(SqlString, null);
}
/// <summary>
/// 返回第一行
/// </summary>
/// <param name="SqlString"></param>
/// <returns></returns>
public DataRow ExecuteDataTableRow(string SqlString, MySqlParameter[] parms)
{
SleepOrGo();
bool frist = true;
Retry:
if (Conn == null || Conn.State != ConnectionState.Open)
ConnTo();
try
{
CmdIni();
cmd.CommandText = SqlString;
if (parms != null)
foreach (MySqlParameter pram in parms)
cmd.Parameters.Add(pram);
DataSet ds = new DataSet();
MySqlDataAdapter adapter = new MySqlDataAdapter();
adapter.SelectCommand = cmd;
adapter.Fill(ds);
DataTable dt = ds.Tables[0];
if (dt.Rows.Count > 0)
return dt.Rows[0];
}
catch (Exception e)
{
if (frist)
{
frist = false;
ErrorDoing(e.Message);
goto Retry;
}
AddError(e.Message, SqlString);
}
finally
{
CloseReader();
IsRunning = false;
}
return null;
}
/// <summary>
/// 返回第一个执行结果
/// </summary>
/// <param name="SqlString"></param>
/// <returns></returns>
public int ExecuteRowCount(string SqlString)
{
string f = ExecuteFirst(SqlString, null);
int c;
int.TryParse(f, out c);
return c;
}
/// <summary>
/// 返回第一个执行结果
/// </summary>
/// <param name="SqlString"></param>
/// <returns></returns>
public string ExecuteFirst(string SqlString)
{
return ExecuteFirst(SqlString, null);
}
/// <summary>
/// 返回第一个执行结果
/// </summary>
/// <param name="SqlString"></param>
/// <returns></returns>
public int ExecuteFirstInt(string SqlString)
{
string id = ExecuteFirst(SqlString, null);
int i;
int.TryParse(id, out i);
return i;
}
/// <summary>
/// 返回第一个值
/// </summary>
/// <param name="SqlString"></param>
/// <returns></returns>
public string ExecuteFirst(string SqlString, MySqlParameter[] parms)
{
SleepOrGo();
bool frist = true;
Retry:
if (Conn == null || Conn.State != ConnectionState.Open)
ConnTo();
try
{
CmdIni();
cmd.CommandText = SqlString;
if (parms != null)
foreach (MySqlParameter pram in parms)
cmd.Parameters.Add(pram);
reader = cmd.ExecuteReader();
if (reader.Read())
return reader[0].ToString();
return "";
}
catch (Exception e)
{
if (e.Message.Contains("Illegal mix of collations"))
return null;
if (frist)
{
frist = false;
ErrorDoing(e.Message);
goto Retry;
}
AddError(e.Message, SqlString);
}
finally
{
CloseReader();
IsRunning = false;
}
return null;
}
/// <summary>
/// 返回插入ID
/// </summary>
/// <param name="SqlString"></param>
/// <returns></returns>
public long ExecuteInsertId(string SqlString)
{
return ExecuteInsertId(SqlString, null);
}
/// <summary>
/// 返回第一个值
/// </summary>
/// <param name="SqlString"></param>
/// <returns></returns>
public long ExecuteInsertId(string SqlString, MySqlParameter[] parms)
{
SleepOrGo();
bool frist = true;
Retry:
if (Conn == null || Conn.State != ConnectionState.Open)
ConnTo();
try
{
CmdIni();
cmd.CommandText = SqlString;
if (parms != null)
foreach (MySqlParameter pram in parms)
cmd.Parameters.Add(pram);
cmd.ExecuteNonQuery();
long id = cmd.LastInsertedId;
return id;
}
catch (Exception e)
{
if (e.Message.Contains(" for key 'PRIMARY'") && e.Message.Contains("Duplicate entry"))
return 0;
if (frist)
{
frist = false;
ErrorDoing(e.Message);
goto Retry;
}
AddError(e.Message, SqlString);
}
finally
{
CloseReader();
IsRunning = false;
}
return 0;
}
/// <summary>
/// 无返回
/// </summary>
/// <param name="SqlString"></param>
/// <returns></returns>
public bool ExecuteNonQuery(string SqlString)
{
return ExecuteNonQuery(SqlString, null);
}
/// <summary>
/// 只保留mysql可识别的字符串
/// </summary>
/// <param name="text"></param>
public string JustUtf8Words(string text)
{
JustUtf8Words(ref text);
return text;
}
/// <summary>
/// 只保留mysql可识别的字符串
/// </summary>
/// <param name="text"></param>
public void JustUtf8Words(ref string text)
{
if (string.IsNullOrEmpty(text))
return;
var cs = text.ToCharArray();
List<char> cc = new List<char>();
foreach (char c in cs)
{
if (c > 7814 && c < 8416 || c > 57096 && c < 59501 || c > 63707 && c < 64309 || c > 65505 || c < 0)
{
if (cc.Contains(c))
continue;
text = text.Replace(c.ToString(), "");
cc.Add(c);
}
}
}
/// <summary>
/// 执行无返回SQL语句
/// </summary>
/// <param name="SqlString">SQL语句</param>
/// <param name="parms">Sql参数</param>
///<returns>是否执行成功</returns>
public bool ExecuteNonQuery(string SqlString, MySqlParameter[] parms)
{
SleepOrGo();
bool frist = true;
Retry:
if (Conn == null || Conn.State != ConnectionState.Open)
ConnTo();
try
{
CmdIni();
cmd.CommandText = SqlString;
if (parms != null)
foreach (MySqlParameter pram in parms)
cmd.Parameters.Add(pram);
cmd.ExecuteNonQuery();
return true;
}
catch (Exception e)
{
if (e.Message.Contains("Illegal mix of collations") || e.Message.Contains("Incorrect string value")
|| e.Message.Contains(" for key 'PRIMARY'") && e.Message.Contains("Duplicate entry"))
return false;
if (frist)
{
frist = false;
ErrorDoing(e.Message);
goto Retry;
}
AddError(e.Message, SqlString);
return false;
}
finally
{
CloseReader();
IsRunning = false;
}
}
/// <summary>
/// 判断是否存在
/// </summary>
/// <param name="SqlString"></param>
/// <returns></returns>
public bool ExecuteExists(string SqlString)
{
return ExecuteExists(SqlString, null);
}
/// <summary>
/// 查询是否存在
/// </summary>
/// <param name="SqlString">SQL语句</param>
/// <param name="parms">SQL参数</param>
/// <returns>是否存在</returns>
public bool ExecuteExists(string SqlString, MySqlParameter[] parms)
{
SleepOrGo();
bool frist = true;
Retry:
if (Conn == null || Conn.State != ConnectionState.Open)
ConnTo();
try
{
CmdIni();
cmd.CommandText = SqlString;
if (parms != null)
foreach (MySqlParameter pram in parms)
cmd.Parameters.Add(pram);
reader = cmd.ExecuteReader();
if (reader.Read())
return true;
return false;
}
catch (Exception e)
{
if (frist)
{
frist = false;
ErrorDoing(e.Message);
goto Retry;
}
AddError(e.Message, SqlString);
return false;
}
finally
{
CloseReader();
IsRunning = false;
}
}
/// <summary>
/// 停止还是前进
/// </summary>
private void SleepOrGo()
{
int i = 0;
while (IsRunning && i < 300)
{
Thread.Sleep(100);
i++;
}
IsRunning = true;
}
/// <summary>
/// 初始化CMD
/// </summary>
private void CmdIni()
{
if (reader != null && !reader.IsClosed)
reader.Close();
if (cmd != null)
cmd.Dispose();
cmd = new MySqlCommand();
cmd.Connection = Conn;
cmd.CommandType = CommandType.Text;
cmd.CommandTimeout = TimeOut;
}
/// <summary>
/// 连接数据库
/// </summary>
private void ConnTo()
{
Close();
try
{
Conn = new MySqlConnection(ConnString);
Conn.Open();
}
catch (Exception e)
{
AddError(e.Message, ConnString);
}
}
/// <summary>
/// 错误信息
/// </summary>
/// <param name="message"></param>
/// <param name="sql"></param>
private void AddError(string message, string sql)
{
if (string.IsNullOrEmpty(message) || message.Contains("Illegal mix of collations"))
return;
ErrorDoing(message);
string errStr = "数据库连接错误:" + message + "\r\nSQL语句:" + sql;
try
{
if (!Directory.Exists("Log"))
{
Directory.CreateDirectory("Log");
}
File.AppendAllText("Log\\log-" + DateTime.Now.ToString("yyyyMMdd") + ".txt", errStr);
}
catch (Exception ex)
{
}
}
/// <summary>
/// 关闭数据库链接
/// </summary>
public void Close()
{
IsRunning = false;
try
{
if (Conn != null && Conn.State == ConnectionState.Open)
Conn.Close();
Conn = null;
try
{
if (reader != null && !reader.IsClosed)
reader.Close();
}
catch
{
}
reader = null;
}
catch
{
}
}
}
public class MysqlKeyValues
{
public List<MysqlKeyValue> List = new List<MysqlKeyValue>();
}
public class MysqlKeyValue
{
public MysqlKeyValue(string key, object value)
{
Key = key;
Value = value == null ? "" : MysqlUtils.ReplaceSqlSpecial(value.ToString());
}
public string Key = "";
public string Value;
}
}
@@ -0,0 +1,658 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
namespace KJD_Web.Utils
{
public static class RegexUtils
{
/// <summary>
/// 返回正则对象所有结果
/// </summary>
/// <param name="HtmlString"></param>
/// <param name="RegexString"></param>
/// <returns></returns>
public static MatchCollection GetMatchRegex(string HtmlString, string RegexString)
{
if (HtmlString == null)
{
//LogSave.Add("匹配正则发生错误:原始字符串为空,正则:" + RegexString);
return null;
}
return Regex.Matches(HtmlString, RegexString, RegexOptions.IgnoreCase);
}
/// <summary>
/// 返回正则对象所有结果
/// </summary>
/// <param name="HtmlString"></param>
/// <param name="RegexString"></param>
/// <returns></returns>
public static MatchCollection GetMatchRegex(ref string HtmlString, string RegexString)
{
if (HtmlString == null)
{
//LogSave.Add("匹配正则发生错误:原始字符串为空,正则:" + RegexString);
return null;
}
return Regex.Matches(HtmlString, RegexString, RegexOptions.IgnoreCase);
}
/// <summary>
/// 返回单个正则分析结果
/// </summary>
/// <param name="HtmlString"></param>
/// <param name="RegexString"></param>
/// <returns></returns>
public static string GetMatchRegexString(ref string HtmlString, string RegexString)
{
if (HtmlString == null)
{
//LogSave.Add("匹配正则发生错误:原始字符串为空,正则:" + RegexString);
return null;
}
MatchCollection mc = Regex.Matches(HtmlString, RegexString, RegexOptions.IgnoreCase);
if (mc.Count > 0)
{
return mc[0].Groups[1].Value.ToString();
}
return null;
}
/// <summary>
/// 返回单个正则分析结果
/// </summary>
/// <param name="HtmlString"></param>
/// <param name="RegexString"></param>
/// <returns></returns>
public static string GetMatchMaxRegexString(ref string HtmlString, string RegexString)
{
if (HtmlString == null)
{
//LogSave.Add("匹配正则发生错误:原始字符串为空,正则:" + RegexString);
return null;
}
MatchCollection mc = Regex.Matches(HtmlString, RegexString, RegexOptions.IgnoreCase);
if (mc.Count > 0)
{
return mc[mc.Count - 1].Groups[1].Value.ToString();
}
return null;
}
/// <summary>
/// 返回匹配的数值
/// </summary>
/// <param name="HtmlString"></param>
/// <param name="RegexString"></param>
/// <returns></returns>
public static int GetMatchInt(ref string HtmlString, string RegexString)
{
string id = GetMatchRegexString(ref HtmlString, RegexString);
int i;
int.TryParse(id, out i);
return i;
}
/// <summary>
/// 返回单个正则分析结果
/// </summary>
/// <param name="HtmlString"></param>
/// <param name="RegexString"></param>
/// <returns></returns>
public static string GetMatchRegexString(string HtmlString, string RegexString)
{
if (HtmlString == null)
{
//LogSave.Add("匹配正则发生错误:原始字符串为空,正则:" + RegexString);
return null;
}
MatchCollection mc = Regex.Matches(HtmlString, RegexString, RegexOptions.IgnoreCase);
if (mc.Count > 0)
{
return mc[0].Groups[1].ToString();
}
return null;
}
/// <summary>
/// 是否存在匹配
/// </summary>
/// <param name="HtmlString"></param>
/// <param name="RegexString"></param>
/// <returns></returns>
public static bool MatchRegex(string HtmlString, string RegexString)
{
if (HtmlString == null)
{
//LogSave.Add("匹配正则发生错误:原始字符串为空,正则:" + RegexString);
return false;
}
return Regex.IsMatch(HtmlString, RegexString, RegexOptions.IgnoreCase);
}
/// <summary>
/// 根据正则删除表达式所匹配的内容
/// </summary>
/// <param name="HtmlString"></param>
/// <param name="RegexString"></param>
/// <returns></returns>
public static string Clear(string HtmlString, string RegexString)
{
if (HtmlString == null)
{
//LogSave.Add("匹配正则发生错误:原始字符串为空,正则:" + RegexString);
return null;
}
return Regex.Replace(HtmlString, RegexString, "", RegexOptions.IgnoreCase);
}
/// <summary>
/// 清除HTML代码
/// </summary>
/// <param name="HtmlString"></param>
/// <returns>返回文字内容</returns>
public static string ClearHtml(string HtmlString)
{
if (HtmlString == null)
{
//LogSave.Add("匹配正则发生错误:原始字符串为空");
return null;
}
return Regex.Replace(Regex.Replace(HtmlString,
@"(<head[\w\W]*?</head>|<script[\w\W]*?</script>|<style[\w\W]*?</style>|<!--[\w\W]*?-->)", ""), "(<[^>]*?>)", "").Trim();
}
/// <summary>
/// 清除HTML代码
/// </summary>
/// <param name="HtmlString"></param>
/// <returns>返回文字内容</returns>
public static string ClearHtml(ref string HtmlString)
{
if (HtmlString == null)
{
//LogSave.Add("匹配正则发生错误:原始字符串为空");
return null;
}
return Regex.Replace(Regex.Replace(HtmlString,
@"(<head[\w\W]*?</head>|<script[\w\W]*?</script>|<style[\w\W]*?</style>|<!--[\w\W]*?-->)", ""), "(<[^>]*?>)", "").Trim();
}
/// <summary>
/// 清除HTML代码
/// </summary>
/// <param name="HtmlString"></param>
/// <returns>返回文字内容</returns>
public static void ClearHtmlX(ref string HtmlString)
{
if (string.IsNullOrEmpty(HtmlString))
{
//LogSave.Add("匹配正则发生错误:原始字符串为空");
return;
}
HtmlString = Regex.Replace(Regex.Replace(HtmlString,
@"(<head[\w\W]*?</head>|<script[\w\W]*?</script>|<style[\w\W]*?</style>|<!--[\w\W]*?-->)", ""), "(<[^>]*?>)", "");
}
/// <summary>
/// 清除HTML代码A标签
/// </summary>
/// <param name="HtmlString"></param>
/// <returns>返回文字内容</returns>
public static string ClearA(string HtmlString)
{
if (HtmlString == null)
{
//LogSave.Add("匹配正则发生错误:原始字符串为空");
return null;
}
HtmlString = Regex.Replace(HtmlString, "(</?a[^>]*>)", "", RegexOptions.IgnoreCase);
return HtmlString.Trim();
}
/// <summary>
/// 去除空格和特殊空白
/// </summary>
/// <param name="text"></param>
/// <returns></returns>
public static string Trim(string text)
{
if (string.IsNullOrEmpty(text))
return "";
return text.Replace("\t", " ").Replace("\r\n", " ").Replace("\r", " ").Replace("\n", " ").Trim();
}
/// <summary>
/// 清除HTML代码A标签
/// </summary>
/// <param name="HtmlString"></param>
/// <returns>返回文字内容</returns>
public static string ClearTitle(string HtmlString)
{
if (HtmlString == null)
{
//LogSave.Add("匹配正则发生错误:原始字符串为空");
return null;
}
HtmlString = Regex.Replace(HtmlString, "(title=\"[^\"]*\")", "");
return HtmlString.Trim();
}
/// <summary>
/// 获取值
/// </summary>
/// <param name="html"></param>
/// <param name="reg"></param>
/// <returns></returns>
public static string GetValue(string html, string reg)
{
return GetMatchRegexString(html, "<" + reg + ">([^<]+)</" + reg + ">");
}
/// <summary>
/// 清理多余的HTML元素
/// </summary>
/// <param name="html"></param>
/// <returns></returns>
public static string ClearNone(string html)
{
if (string.IsNullOrEmpty(html))
return null;
if (html.Contains("\0") && html.IndexOf("\0") > 0)
html = html.Substring(0, html.IndexOf("\0"));
string h = Clear(html, @"(<\!doctype[^>]*?>)");
h = Clear(h, @"(<html[^>]*?>)");
h = Clear(h, @"(<head[\w\W]*?</head>)");
h = Clear(h, @"(<script[\w\W]*?</script>)");
h = Clear(h, @"(<style[\w\W]*?</style>)");
h = Clear(h, @"(<input[^>]*?>)");
h = Clear(h, @"(<!--[\w\W]*?-->)");
h = Clear(h, @"(<link[^>]*?>)");
h = Clear(h, @"(\s*alt\s*=[""'\s]*[^>]*?['""]+)");
h = Clear(h, @"(\s*style\s*=[""'\s]*[^>]*?['""]+)");
h = Clear(h, @"(\s*title\s*=[""'\s]*[^>]*?['""]+)");
h = Clear(h, @"(\s*id\s*=[""'\s]*[^>]*?['""]+)");
h = Clear(h, @"(\s*class\s*=[""'\s]*[^>]*?['""]+)");
h = Clear(h, @"(\s*align\s*=[""'\s]*[^>]*?['""]+)");
h = h.Replace("\r\n", " ");
h = h.Replace("\n", " ").Replace("\r", " ").Replace("\t", " ");
h = h.Replace(" ", " ");
h = h.Replace(" ", " ");
h = h.Replace(" ", " ");
h = h.Replace(" ", " ");
return h.Replace(" ", " ").Replace(" ", " ");
}
/// <summary>
/// 返回执行结果数
/// </summary>
/// <param name="html"></param>
/// <param name="regex"></param>
/// <returns></returns>
public static int GetRegexCount(string html, string regex)
{
if (html == null)
{
//LogSave.Add("匹配正则发生错误:原始字符串为空,正则:" + regex);
return 0;
}
return Regex.Matches(html, regex, RegexOptions.IgnoreCase).Count;
}
/// <summary>
/// 根据正则删除表达式所匹配的内容
/// </summary>
/// <param name="HtmlString"></param>
/// <param name="RegexString"></param>
/// <returns></returns>
public static string Relpace(string HtmlString, string RegexString, string NewString)
{
if (HtmlString == null)
return null;
return Regex.Replace(HtmlString, RegexString, NewString, RegexOptions.IgnoreCase);
}
/// <summary>
/// 根据正则删除表达式所匹配的内容
/// </summary>
/// <param name="HtmlString"></param>
/// <param name="RegexString"></param>
/// <returns></returns>
public static void Relpace(ref string HtmlString, string RegexString, string NewString)
{
if (HtmlString == null)
return;
HtmlString = Regex.Replace(HtmlString, RegexString, NewString, RegexOptions.IgnoreCase);
}
/// <summary>
/// 关键词在文本中出现的次数
/// </summary>
/// <param name="b"></param>
/// <param name="keyword"></param>
/// <returns></returns>
public static int GetStringCount(ref byte[] b, string keyword)
{
if (string.IsNullOrEmpty(keyword))
return 0;
int c = 0;
bool had;
byte[] b1 = Encoding.UTF8.GetBytes(keyword);
for (int i = 0; i < b.Length - b1.Length; i++)
{
had = false;
for (int j = 0; j < b1.Length; j++)
{
if (b[i + j] != b1[j])
{
had = true;
break;
}
}
if (had)
{
c++;
i += b1.Length - 1;
}
}
return c;
}
/// <summary>
/// 是否存在
/// </summary>
/// <param name="html"></param>
/// <param name="reg"></param>
/// <returns></returns>
public static bool Exists(string html, string reg)
{
if (string.IsNullOrEmpty(html) || string.IsNullOrEmpty(reg))
return false;
return new Regex(reg).IsMatch(html);
}
/// <summary>
/// 是否是数字
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static bool IsNumber(string str)
{
System.Text.RegularExpressions.Regex reg1 = new System.Text.RegularExpressions.Regex(@"^[0-9\.]+$");
return reg1.IsMatch(str);
}
/// <summary>
/// 是否是字母
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static bool IsChar(string str)
{
System.Text.RegularExpressions.Regex reg1 = new System.Text.RegularExpressions.Regex(@"^[A-Za-z]+$");
return reg1.IsMatch(str);
}
/// <summary>
/// 是否是字母
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static bool IsCharOrNumber(string str)
{
System.Text.RegularExpressions.Regex reg1 = new System.Text.RegularExpressions.Regex(@"^[A-Za-z0-9]+$");
return reg1.IsMatch(str);
}
/// <summary>
/// 是否是中文字符串列
/// </summary>
/// <param name="word"></param>
/// <returns></returns>
public static bool IsWordList(string word)
{
char[] xj = word.ToCharArray();
for (int j = 0; j < xj.Length; j++)
if (!IsWord(xj[j]))
return false;
return true;
}
/// <summary>
/// 是否是字符
/// </summary>
/// <param name="ascii"></param>
/// <returns></returns>
private static bool IsWord(int ascii)
{
if (ascii == 32 || ascii == 35) //空格
return true;
if (ascii < 58 && ascii > 47) //数字
return true;
if (ascii < 48 && ascii > 31) //符号
return true;
if (ascii < 91 && ascii > 64) //小写字母
return true;
if (ascii < 123 && ascii > 96) //大写字母
return true;
if (ascii < 40892 && ascii > 13311) //中文字符串
return true;
return false;
}
/// <summary>
/// 获取值
/// </summary>
/// <param name="html"></param>
/// <param name="reg"></param>
/// <returns></returns>
public static bool GetBoolValue(string html, string reg)
{
string temp = GetMatchRegexString(html, "<" + reg + ">([^<]+)</" + reg + ">");
if (!string.IsNullOrEmpty(temp) && (temp.ToLower() == "true" || temp == "1"))
return true;
return false;
}
/// <summary>
/// 获取值
/// </summary>
/// <param name="html"></param>
/// <param name="reg"></param>
/// <returns></returns>
public static int GetIntValue(string html, string reg)
{
string temp = GetMatchRegexString(html, "<" + reg + ">([^<]+)</" + reg + ">");
int i;
if (int.TryParse(temp, out i))
return i;
return 0;
}
/// <summary>
/// 获取值
/// </summary>
/// <param name="html"></param>
/// <param name="reg"></param>
/// <returns></returns>
public static long GetLongValue(string html, string reg)
{
string temp = GetMatchRegexString(html, "<" + reg + ">([^<]+)</" + reg + ">");
long i;
if (long.TryParse(temp, out i))
return i;
return 0;
}
/// <summary>
/// 获取值
/// </summary>
/// <param name="html"></param>
/// <param name="reg"></param>
/// <returns></returns>
public static double GetDoubleValue(string html, string reg)
{
string temp = GetMatchRegexString(html, "<" + reg + ">([^<]+)</" + reg + ">");
double i;
if (double.TryParse(temp, out i))
return i;
return 0;
}
/// <summary>
/// 获取值
/// </summary>
/// <param name="html"></param>
/// <param name="reg"></param>
/// <returns></returns>
public static DateTime GetDateValue(string html, string reg)
{
string temp = GetMatchRegexString(html, "<" + reg + ">([^<]+)</" + reg + ">");
DateTime i;
if (DateTime.TryParse(temp, out i))
return i;
return DateTime.MinValue;
}
/// <summary>
/// 获取值
/// </summary>
/// <param name="html"></param>
/// <param name="reg"></param>
/// <returns></returns>
public static decimal GetDecimalValue(string html, string reg)
{
string temp = GetMatchRegexString(html, "<" + reg + ">([^<]+)</" + reg + ">");
decimal i = 0;
if (decimal.TryParse(temp, out i))
return i;
return 0;
}
/// <summary>
/// 获取值
/// </summary>
/// <param name="html"></param>
/// <param name="reg"></param>
/// <returns></returns>
public static decimal GetDecimalJson(ref string html, string reg)
{
string temp = GetMatchRegexString(html, @"['""]" + reg + @"['""][\s]*:[\s]*['""]([^']+?)['""]");
if (string.IsNullOrEmpty(temp))
temp = GetMatchRegexString(html, @"['""]" + reg + @"['""][\s]*:[\s]*([\d-\.]+)");
decimal i = 0;
if (decimal.TryParse(temp, out i))
return i;
return 0;
}
/// <summary>
/// 获取值
/// </summary>
/// <param name="html"></param>
/// <param name="reg"></param>
/// <returns></returns>
public static int GetIntJson(ref string html, string reg)
{
string temp = GetMatchRegexString(html, @"['""]" + reg + @"['""][\s]*:[\s]*['""]([^']+?)['""]");
if (string.IsNullOrEmpty(temp))
temp = GetMatchRegexString(html, @"['""]" + reg + @"['""][\s]*:[\s]*([\d-]+)");
int i;
if (int.TryParse(temp, out i))
return i;
return 0;
}
/// <summary>
/// 时间戳转字符串时间
/// </summary>
/// <param name="html"></param>
/// <param name="reg"></param>
/// <returns></returns>
public static string GetIntTimeToString(ref string html, string reg)
{
return GetIntTimeToString(ref html, reg, 0);
}
/// <summary>
/// 时间戳转字符串时间
/// </summary>
/// <param name="html"></param>
/// <param name="reg"></param>
/// <param name="addTime">添加时间</param>
/// <returns></returns>
public static string GetIntTimeToString(ref string html, string reg, int addTime)
{
int time = GetIntJson(ref html, reg) + addTime;
DateTime dt = TimeUtils.StampToDateTime(time);
return dt.ToString("yyyy-MM-dd HH:mm:ss");
}
/// <summary>
/// 获取值
/// </summary>
/// <param name="html"></param>
/// <param name="reg"></param>
/// <returns></returns>
public static long GetLongJson(ref string html, string reg)
{
string temp = GetMatchRegexString(html, @"['""]" + reg + @"['""][\s]*:[\s]*['""]([^']+?)['""]");
if (string.IsNullOrEmpty(temp))
temp = GetMatchRegexString(html, @"['""]" + reg + @"['""][\s]*:[\s]*([\d]+)");
long i;
if (long.TryParse(temp, out i))
return i;
return 0;
}
/// <summary>
/// 获取值
/// </summary>
/// <param name="html"></param>
/// <param name="reg"></param>
/// <returns></returns>
public static string GetStringJson(ref string html, string reg)
{
string temp = GetMatchRegexString(html, @"[""]" + reg + @"[""][\s]*:[\s]*[""]([^""]+?)[""]");
if (temp == null)
temp = GetMatchRegexString(html, @"[""]" + reg + @"[""][\s]*:[\s]*[""]([^""]*?)[""]");
if (temp == null)
temp = GetMatchRegexString(html, @"[']" + reg + @"['][\s]*:[\s]*[']([^']*?)[']");
if (temp == null)
temp = GetMatchRegexString(html, @"['""]" + reg + @"['""][\s]*:[\s]*([\d]+)");
return temp;
}
/// <summary>
/// 获取值
/// </summary>
/// <param name="html"></param>
/// <param name="reg"></param>
/// <returns></returns>
public static string GetStringInput(ref string html, string reg)
{
string temp = GetMatchRegexString(html, @"<input [^>]*?name=['""]" + reg + @"[""'][^>]+?value=[""']([^>]+)[""'][^>]*>");
if (string.IsNullOrEmpty(temp))
temp = GetMatchRegexString(html, @"<input [^>]*?value=[""']([^>]+)[""'][^>]+?name=['""]" + reg + @"[""'][^>]*>");
return temp;
}
/// <summary>
/// 获取值
/// </summary>
/// <param name="html"></param>
/// <param name="key"></param>
/// <returns></returns>
public static string GetStringQuery(ref string queryString, string key)
{
queryString = "&" + queryString;
int nIndex = queryString.IndexOf("&" + key + "=");
if (nIndex == -1)
return null;
string temp = queryString.Substring(nIndex).Replace("&" + key + "=", "");
nIndex = temp.IndexOf('&');
if (nIndex > -1)
temp = temp.Substring(0, nIndex);
return temp;
}
public static string FliterHtmlTag(string htmlStr)
{
if (String.IsNullOrEmpty(htmlStr))
{
return "";
}
string regEx_style = "<style[^>]*?>[\\s\\S]*?<\\/style>"; //定义style的正则表达式
string regEx_script = "<script[^>]*?>[\\s\\S]*?<\\/script>"; //定义script的正则表达式
string regEx_html = "<[^>]+>"; //定义HTML标签的正则表达式
htmlStr = Regex.Replace(htmlStr, regEx_style, "");//删除css
htmlStr = Regex.Replace(htmlStr, regEx_script, "");//删除js
htmlStr = Regex.Replace(htmlStr, regEx_html, "");//删除html标记
htmlStr = Regex.Replace(htmlStr, "\\s*|\t|\r|\n", "");//去除tab、空格、空行
htmlStr = htmlStr.Replace("\"", "");//去除异常的引号
return htmlStr.Trim();
}
}
}
@@ -0,0 +1,23 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace KJD_Web.Utils
{
public class TimeUtils
{
/// <summary>
/// 时间戳转为C#格式时间
/// </summary>
/// <param name="timeStamp"></param>
/// <returns></returns>
public static DateTime StampToDateTime(int timeStamp)
{
DateTime dateTimeStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
long lTime = long.Parse(timeStamp + "0000000");
TimeSpan toNow = new TimeSpan(lTime);
return dateTimeStart.Add(toNow);
}
}
}