using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Net;
using Newtonsoft.Json.Serialization;
using System.Collections;
using PublicCode.SystemManage;
using System.IO.Compression;
namespace Helpers
{
///
/// 个人常用工具箱
///
public static partial class Tool
{
///
/// 打印日志
///
///
public static bool PrintLog(string title, string content)
{
try
{
string path = GetSystemConfig().LogPath;
CreateLogDirectory(path);
//往指定文件中追加日志
StreamWriter sw = new StreamWriter(string.Format("{0}", path) + DateTime.Now.ToString("yyyy-MM-dd") + "-log.txt", true, Encoding.UTF8);
sw.WriteLine("产生时间:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));
sw.WriteLine("\t" + title);
sw.WriteLine(content);
sw.WriteLine();
sw.WriteLine();
sw.Close();
sw.Dispose();
return true;
}
catch
{
return false;
}
}
///
/// 打印错误日志
///
///
public static bool PrintLog_Error(string title, string content)
{
try
{
string path = GetSystemConfig().ErrorLogPath;
CreateLogDirectory(path);
//往指定文件中追加日志
StreamWriter sw = new StreamWriter(string.Format("{0}", path) + DateTime.Now.ToString("yyyy-MM-dd") + "-error_log.txt", true, Encoding.UTF8);
sw.WriteLine("产生时间:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));
sw.WriteLine("\t" + title);
sw.WriteLine(content);
sw.WriteLine();
sw.WriteLine();
sw.Close();
sw.Dispose();
return true;
}
catch
{
return false;
}
}
///
/// 打印信息日志
///
///
public static bool PrintLog_Info(string title, string content)
{
try
{
string path = GetSystemConfig().InfoLogPath;
CreateLogDirectory(path);
//往指定文件中追加日志
StreamWriter sw = new StreamWriter(string.Format("{0}", path) + DateTime.Now.ToString("yyyy-MM-dd") + "-info_log.txt", true, Encoding.UTF8);
sw.WriteLine("产生时间:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));
sw.WriteLine("\t" + title);
sw.WriteLine(content);
sw.WriteLine();
sw.WriteLine();
sw.Close();
sw.Dispose();
return true;
}
catch
{
return false;
}
}
///
/// 打印字符串到txt
///
/// 打印的内容
/// 文件路径(不含后缀)
/// 是否为追加
///
public static bool PrintStrToTxt(string content, string path, bool isAppend)
{
try
{
//往指定文件中追加日志
StreamWriter sw = new StreamWriter(path, isAppend, Encoding.UTF8);
sw.WriteLine(content);
sw.WriteLine();
sw.Close();
sw.Dispose();
return true;
}
catch
{
return false;
}
}
///
/// 读取指定的文件(UTF-8)
///
/// 文件路径
///
public static string GetTxt(string path)
{
StreamReader sr = new StreamReader(path, Encoding.UTF8);
string str = sr.ReadToEnd();
sr.Close();
sr.Dispose();
return str;
}
///
/// 将对象转换成字符串类型
///
/// 传入的对象
///
public static string ObjectToString(object obj)
{
var json = Newtonsoft.Json.JsonConvert.SerializeObject(obj);
return json.ToString();
}
///
/// 取得标准化的当前时间(yyyy-MM-dd HH:mm:ss.fff)
///
///
public static DateTime GetNowDate()
{
return DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));
}
///
/// 将字典转换成URL参数格式(a=1&b=2)
///
public static string DicToUrlParam(Dictionary dic) {
string paramStr = string.Empty;
foreach (KeyValuePair kv in dic)
{
paramStr += $"{kv.Key}={kv.Value}";
paramStr += "&";
}
if (!string.IsNullOrWhiteSpace(paramStr)) {
paramStr = paramStr.Remove(paramStr.Length - 1);
}
return paramStr;
}
///
/// 将字典按参数名排序转换成URL参数格式(a=1&b=2)
///
/// 排序方式
///
public static string DicToUrlParam(Dictionary dic, SortType sortType) {
if (sortType == SortType.asc) {
dic = (Dictionary)dic.OrderBy(o => o.Key, StringComparer.OrdinalIgnoreCase);
} else {
dic = (Dictionary)dic.OrderByDescending(o => o.Key, StringComparer.OrdinalIgnoreCase);
}
return DicToUrlParam(dic);
}
///
/// 发送post请求
///
/// 请求路径
/// 要提交的参数字符串
/// ContentType
///
public static string HttpPost(string Url, string postDataStr, string ContentType = "application/x-www-form-urlencoded")//发送post请求
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
request.Method = "POST";
request.ContentType = ContentType;
request.ContentLength = postDataStr.Length;
StreamWriter writer = new StreamWriter(request.GetRequestStream(), Encoding.ASCII);
writer.Write(postDataStr);
writer.Flush();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
string encoding = response.ContentEncoding;
if (encoding == null || encoding.Length < 1)
{
encoding = "UTF-8"; //默认编码
}
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(encoding));
string retString = reader.ReadToEnd();
return retString;
}
///
/// 发送post请求
///
/// 请求路径
/// 要提交的参数字符串
/// ContentType
///
public static Stream HttpPostForStream(string Url, string postDataStr,string ContentType= "application/x-www-form-urlencoded") {
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
request.Method = "POST";
request.ContentType = ContentType;
request.ContentLength = postDataStr.Length;
StreamWriter writer = new StreamWriter(request.GetRequestStream(), Encoding.ASCII);
writer.Write(postDataStr);
writer.Flush();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
string encoding = response.ContentEncoding;
if (encoding == null || encoding.Length < 1)
{
encoding = "UTF-8"; //默认编码
}
return response.GetResponseStream();
}
///
/// 发送post请求
///
/// 请求路径
/// 要提交的参数字符串
/// 携带的头部名
/// 携带的头部信息
///
public static string HttpPost(string Url, string postDataStr, string headName, string headValue)//发送post请求
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = postDataStr.Length;
request.Headers.Add(headName, headValue); //添加header
StreamWriter writer = new StreamWriter(request.GetRequestStream(), Encoding.ASCII);
writer.Write(postDataStr);
writer.Flush();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
string encoding = response.ContentEncoding;
if (encoding == null || encoding.Length < 1)
{
encoding = "UTF-8"; //默认编码
}
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(encoding));
string retString = reader.ReadToEnd();
return retString;
}
///
/// 发送含文件的Post请求
///
/// 请求的路径
/// 发送的参数列表,注意:参数直接写进流里面,需要从MultipartFormDataStreamProvider里面读取,关于Dictionary参数类型,可以json直接转换成Dictionary类型
/// 发送的文件列表<文件名,文件地址>
///
public static string HttpPost(string url, Dictionary postData, Dictionary files)
{
string paramStr = "";
HttpWebRequest request = WebRequest.Create(url + paramStr) as HttpWebRequest;
CookieContainer cookieContainer = new CookieContainer();
request.CookieContainer = cookieContainer;
request.AllowAutoRedirect = true;
request.Method = "POST";
string boundary = DateTime.Now.Ticks.ToString("X"); // 随机分隔线
request.ContentType = "multipart/form-data;charset=utf-8;boundary=" + boundary;
byte[] itemBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "\r\n");
byte[] endBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n");
Stream postStream = request.GetRequestStream();
postStream.Write(itemBoundaryBytes, 0, itemBoundaryBytes.Length);
//写入文本
if (postData != null && postData.Count > 0)
{
var keys = postData.Keys;
foreach (var key in keys)
{
string strHeader = string.Format("Content-Disposition: form-data; name=\"{0}\"\r\n\r\n", key);
byte[] strByte = System.Text.Encoding.UTF8.GetBytes(strHeader);
postStream.Write(strByte, 0, strByte.Length);
byte[] value = System.Text.Encoding.UTF8.GetBytes(string.Format("{0}", postData[key]));
postStream.Write(value, 0, value.Length);
postStream.Write(itemBoundaryBytes, 0, itemBoundaryBytes.Length);
}
}
postStream.Write(itemBoundaryBytes, 0, itemBoundaryBytes.Length);
//写入文件
if (files != null && files.Count > 0)
{
var keys = files.Keys;
foreach (var key in keys)
{
string filePath = files[key];
int pos = filePath.LastIndexOf("\\");
string fileName = filePath.Substring(pos + 1);
StringBuilder sbHeader = new StringBuilder(string.Format("Content-Disposition:form-data;name=\"{0}\";filename=\"{1}\"\r\nContent-Type:application/octet-stream\r\n\r\n", key, fileName));
byte[] postHeaderBytes = Encoding.UTF8.GetBytes(sbHeader.ToString());
FileStream fs = new FileStream(files[key], FileMode.Open, FileAccess.Read);
byte[] bArr = new byte[fs.Length];
fs.Read(bArr, 0, bArr.Length);
fs.Close();
postStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);
postStream.Write(bArr, 0, bArr.Length);
postStream.Write(itemBoundaryBytes, 0, itemBoundaryBytes.Length);
}
}
postStream.Write(endBoundaryBytes, 0, endBoundaryBytes.Length); //结束标志
postStream.Close();
//发送请求并获取相应回应数据
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
//直到request.GetResponse()程序才开始向目标网页发送Post请求
Stream instream = response.GetResponseStream();
StreamReader sr = new StreamReader(instream, Encoding.UTF8);
string content = sr.ReadToEnd();
return content;
}
///
/// 发送Get请求(返回字符串类型)
///
/// 请求路径
/// 返回字符串类型
public static string HttpGet(string Url,string encoding = null)//发送post请求
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
request.Method = "GET";
request.ContentType = "application/x-www-form-urlencoded";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
if (string.IsNullOrWhiteSpace(encoding))
{
encoding = response.ContentEncoding;
if (encoding == null || encoding.Length < 1)
{
encoding = "UTF-8"; //默认编码
}
}
StreamReader reader;
if (encoding == "gzip")
{
var c = new GZipStream(response.GetResponseStream(), CompressionMode.Decompress);
encoding = "UTF-8";
reader = new StreamReader(c, Encoding.GetEncoding(encoding));
}
else
{
reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(encoding));
}
string retString = reader.ReadToEnd();
return retString;
}
///
/// 发送Get请求(返回一个stream流)
///
/// 请求路径
/// 返回一个stream流
public static Stream GetHttpStream(string Url)//发送post请求
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
request.Method = "GET";
request.ContentType = "application/x-www-form-urlencoded";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
string encoding = response.ContentEncoding;
if (encoding == null || encoding.Length < 1)
{
encoding = "UTF-8"; //默认编码
}
return response.GetResponseStream();
}
///
/// 下载资源
///
/// 资源路径
/// 请求参数
/// 资源保存路径(含文件名)
/// 保存后的路径
public static string HttpDownloadFile(string url, string param, string path)
{
byte[] bs = Encoding.UTF8.GetBytes(param);
// 设置参数
HttpWebRequest req = WebRequest.Create(url) as HttpWebRequest;
System.Net.ServicePointManager.Expect100Continue = false;
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = bs.Length;
using (Stream reqStream = req.GetRequestStream())
{
reqStream.Write(bs, 0, bs.Length);
}
//发送请求并获取相应回应数据
HttpWebResponse response = req.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;
}
///
/// 把一个字符串按标识拆分成多个字符串
///
/// 原字符串
/// 截断标识
///
public static List Split(string str, string idstr) {
List result = new List();
//传入字符串不能为空
if (string.IsNullOrEmpty(str)) {
return new List();
//throw new Exception("传入的字符串为空");
}
//传入的标识为空
if (string.IsNullOrEmpty(idstr)) {
string[] strings = str.Split();
result = strings.ToList();
return result;
}
string tempStr = str; //待处理字符串
int idstrLength = idstr.Length; //标识字符串的长度
do {
if (tempStr.IndexOf(idstr) == -1) { result.Add(tempStr); break; } //如果找不到对应的标识,则把整个字符串添加进去
int index = tempStr.IndexOf(idstr); //取得标识字符串所在的位置
result.Add(tempStr.Substring(0, index)); //截断字符串后添加到列表中
tempStr = tempStr.Substring(index + idstrLength); //更新待处理的字符串->去掉截走的部分以及标识部分
} while (!string.IsNullOrEmpty(tempStr)); //如果待处理的字符串不为空则继续处理
return result;
}
///
/// 把一个字符串按标识拆分成多个字符串
///
/// 原字符串
/// 截断标识
/// 是否保留截断标识
///
public static List Split(string str, string idstr, bool isSaveIdstr)
{
if (string.IsNullOrEmpty(str)) {
return new List();
}
if (!isSaveIdstr) {
return Split(str, idstr);
}
List result = new List();
//传入字符串不能为空
if (string.IsNullOrEmpty(str))
{
throw new Exception("传入的字符串为空");
}
//传入的标识为空
if (string.IsNullOrEmpty(idstr))
{
string[] strings = str.Split();
result = strings.ToList();
return result;
}
string tempStr = str; //待处理字符串
int idstrLength = idstr.Length; //标识字符串的长度
do
{
if (tempStr.IndexOf(idstr) == -1) { result.Add(tempStr); break; } //如果找不到对应的标识,则把整个字符串添加进去
int index = tempStr.IndexOf(idstr); //取得标识字符串所在的位置
result.Add(tempStr.Substring(0, index)); //截断字符串后添加到列表中
result.Add(tempStr.Substring(index, idstr.Length)); //将截断标识也存储进去
tempStr = tempStr.Substring(index + idstrLength); //更新待处理的字符串->去掉截走的部分以及标识部分
} while (!string.IsNullOrEmpty(tempStr)); //如果待处理的字符串不为空则继续处理
return result;
}
///
/// 字符串抓取(包含抓取规则中的字符)
///
/// 原始字符串
/// 抓取的字符串规则,例如ab{*}fg,其中'{*}'是自定义通配符,即后面的wildcard
/// 通配符
/// 抓取到的字符串列表
public static List GrabString(string str, string rule, string wildcard)
{
List strs = Helpers.Tool.Split(rule, wildcard, true); //把标识字符串按{*}拆分
List getStr = new List();//存储抓取到的字符串
string tempStr = str;
do
{
string oneStr = ""; //记录字符串变量
int beginPosition = 0; //开始位置
int endPosition = 0; //结束位置
if (strs.Count == 1 && strs[0] == wildcard)
{ //如果只输入了{*} 则直接抓取全部
oneStr = tempStr;
}
//遍历规则
for (int i = 0; i < strs.Count; i++)
{
if (i > 0)
{
if (strs[i - 1] == wildcard)// 如果匹配规则是通配符,由当前开始取,直到结束值
{
endPosition = tempStr.IndexOf(strs[i]); //取得单次结束的位置
if (endPosition == -1) //如果找不到结尾的位置,则直接取到结尾
{
oneStr += tempStr;
}
else
{ //如果有结尾
endPosition += strs[i].Length; //取结尾位置
oneStr += tempStr.Substring(beginPosition, endPosition); //取字符串
beginPosition = endPosition; //开始位置变更为结尾位置
endPosition = 0; //结尾位置为初始
tempStr = tempStr.Substring(beginPosition); //刷新检索字符串
beginPosition = 0; //初始化起始位置
}
}
}
else
{
if (strs[i] == wildcard) //如果以通配符开头,则直接跳过
{ continue; }
else
{ //不以通配符开头
beginPosition = tempStr.IndexOf(strs[i]); //找到第一个匹配的位置并记录
if (beginPosition == -1) { tempStr = null; break; }
oneStr += tempStr.Substring(beginPosition, strs[i].Length); //添加到字符串里面
beginPosition += strs[i].Length; //更新开始位置
tempStr = tempStr.Substring(beginPosition); //更新字符串
beginPosition = 0; //初始化起始位置
}
}
}
getStr.Add(oneStr); //添加抓取结果
oneStr = ""; //初始化记录字符串
} while (!string.IsNullOrEmpty(tempStr));
return getStr;
}
///
/// 字符串抓取
///
/// 原始字符串
/// 抓取的字符串规则,例如ab{*}fg,其中'{*}'是自定义通配符,即后面的wildcard
/// 通配符
/// 是否抓取规则中的字符
/// 抓取到的字符串列表
public static List GrabString(string str, string rule, string wildcard, bool isGrabRule)
{
if (isGrabRule) { GrabString(str, rule, wildcard); }
List strs = Helpers.Tool.Split(rule, wildcard, true); //把标识字符串按{*}拆分
List getStr = new List();//存储抓取到的字符串
string tempStr = str;
do
{
string oneStr = ""; //记录字符串变量
int beginPosition = 0; //开始位置
int endPosition = 0; //结束位置
if (strs.Count == 1 && strs[0] == wildcard)
{ //如果只输入了{*} 则直接抓取全部
oneStr = tempStr;
}
//遍历规则
for (int i = 0; i < strs.Count; i++)
{
if (i > 0)
{
if (strs[i - 1] == wildcard)// 如果匹配规则是通配符,由当前开始取,直到结束值
{
endPosition = tempStr.IndexOf(strs[i]); //取得单次结束的位置
if (endPosition == -1) //如果找不到结尾的位置,则直接取到结尾
{
oneStr += tempStr;
}
else
{ //如果有结尾
//endPosition += strs[i].Length; //取结尾位置
oneStr += tempStr.Substring(beginPosition, endPosition); //取字符串
beginPosition = endPosition; //开始位置变更为结尾位置
endPosition = 0; //结尾位置为初始
tempStr = tempStr.Substring(beginPosition); //刷新检索字符串
beginPosition = 0; //初始化起始位置
}
}
}
else
{
if (strs[i] == wildcard) //如果以通配符开头,则直接跳过
{ continue; }
else
{ //不以通配符开头
beginPosition = tempStr.IndexOf(strs[i]); //找到第一个匹配的位置并记录
if (beginPosition == -1) { tempStr = null; break; }
//oneStr += tempStr.Substring(beginPosition, strs[i].Length); //添加到字符串里面
beginPosition += strs[i].Length; //更新开始位置
tempStr = tempStr.Substring(beginPosition); //更新字符串
beginPosition = 0; //初始化起始位置
}
}
}
if (!string.IsNullOrEmpty(oneStr)) {
getStr.Add(oneStr);
}//添加抓取结果
oneStr = ""; //初始化记录字符串
} while (!string.IsNullOrEmpty(tempStr));
return getStr;
}
///
/// 字符串内替换
///
/// 待处理的字符串
/// 要替换的内容
/// 替换成的内容
///
public static string ReplaceString(string str, string oldStr, string newStr) {
if (string.IsNullOrEmpty(str)) { return ""; }
string result = "";
List splitStr = Split(str, oldStr, true); //按替换的串分割字符串
for (int i = 0; i < splitStr.Count; i++)
{
if (splitStr[i] == oldStr)
{
splitStr[i] = newStr;
}
result += splitStr[i];
}
return result;
}
///
/// 获取Core的Json配置
///
///
///
public static SysConfig GetSystemConfig(string ConfigFileName= "appsettings.json") {
try
{
string value = string.Empty;
string Root = AppContext.BaseDirectory;
string json = GetTxt(Root + "\\" + ConfigFileName);
SysConfig config = json.ToModel();
return config;
}
catch
{
throw new Exception("配置读取错误,请检测项目目录下的appsettings.json文件");
}
}
///
/// 检测时间的合法性
///
/// 检测的时间
///
public static bool ValidateDate(DateTime t) {
DateTime min = DateTime.Parse("1753-01-01");
DateTime max = DateTime.Parse("2999-12-31");
if (t < min || t > max)
{
return false;
}
else { return true; }
}
///
/// 格式化时间yyyy-MM-dd,失败返回1970-01-01
///
///
///
public static DateTime FormatDate(DateTime t) {
DateTime result = DateTime.Now;
bool tryResult = DateTime.TryParse(t.ToString("yyyy-MM-dd HH:mm:ss.fff"), out result);
if (tryResult)
{
return result;
}
else {
return DateTime.Parse("1970-01-01");
}
}
///
/// 取得随机字符
///
///
///
public static string GetRandStr(int length) {
if (length < 1) { throw new Exception("长度必须大于0"); }
try
{
string str = "";
Random r = new Random();
int i = 0;
while (i < length)
{
int num = r.Next(48, 122);
if (num > 47 && num < 58)
{
str += num.ToString();
i++;
}
else if (num > 64 && num < 91)
{
str += Convert.ToChar(num).ToString();
i++;
}
else if (num > 96 && num < 123)
{
str += Convert.ToChar(num).ToString();
i++;
}
else { continue; }
}
return str;
}
catch {
return null;
}
}
///
/// 删除指定文件
///
///
///
public static bool DeleteFile(string path) {
try
{
System.IO.File.Delete(path);
return true;
}
catch {
return false;
}
}
///
/// 创建全路径目录
///
///
public static void CreateLogDirectory(string path) {
if (string.IsNullOrEmpty(path))
{
return;
}
string[] paths = path.Split('\\');
string tempPath = "";
foreach (var a in paths)
{
tempPath += a + "\\";
Tool.CreateDirectory(tempPath, ""); //目录不存在的话创建目录
}
}
///
/// 判断传入参数是否为空
///
///
///
public static bool IsNull(params object[] param) {
foreach (var a in param) {
if (a == null) {
return true;
}
if (string.IsNullOrEmpty(a.ToString())) {
return true;
}
}
return false;
}
///
/// 10进制转26进制以字母表示
///
///
/// 传空字符串
///
public static string GetRowIndexStr(int number, ref string str)
{
#region 字符列表处理
string[] chars = new string[26]; //字符列表A,B,C.....X,Y,Z
for (int i = 0; i < 26; i++)
{
chars[i] = ((char)(65 + i)).ToString();
}
#endregion
if (number > 26) //除26后仍大于26,则进一位
{
str = chars[number % 26] + str;
return GetRowIndexStr(number / 26, ref str); //递归调用,使其进一位
}
else //返回最高位
{
str = chars[number % 26] + str;
return str;
}
}
}
///
/// 排序类型
///
public enum SortType {
asc = 1,
desc = 2,
}
}