Moli
2022-04-15 22477f0eca904ec628ab59cd749f959af35c1439
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
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
{
    /// <summary>
    /// 个人常用工具箱
    /// </summary>
    public static partial class Tool
    {
        /// <summary>
        /// 打印日志
        /// </summary>
        /// <returns></returns>
        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;
            }
        }
 
        /// <summary>
        /// 打印错误日志
        /// </summary>
        /// <returns></returns>
        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;
            }
        }
 
        /// <summary>
        /// 打印信息日志
        /// </summary>
        /// <returns></returns>
        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;
            }
        }
 
        /// <summary>
        /// 打印字符串到txt
        /// </summary>
        /// <param name="content">打印的内容</param>
        /// <param name="path">文件路径(不含后缀)</param>
        /// <param name="isAppend">是否为追加</param>
        /// <returns></returns>
        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;
            }
        }
 
        /// <summary>
        /// 读取指定的文件(UTF-8)
        /// </summary>
        /// <param name="path">文件路径</param>
        /// <returns></returns>
        public static string GetTxt(string path)
        {
            StreamReader sr = new StreamReader(path, Encoding.UTF8);
            string str = sr.ReadToEnd();
            sr.Close();
            sr.Dispose();
            return str;
        }
 
        /// <summary>
        /// 将对象转换成字符串类型
        /// </summary>
        /// <param name="obj">传入的对象</param>
        /// <returns></returns>
        public static string ObjectToString(object obj)
        {
            var json = Newtonsoft.Json.JsonConvert.SerializeObject(obj);
            return json.ToString();
        }
 
        /// <summary>
        /// 取得标准化的当前时间(yyyy-MM-dd HH:mm:ss.fff)
        /// </summary>
        /// <returns></returns>
        public static DateTime GetNowDate()
        {
            return DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));
        }
 
        /// <summary>
        /// 将字典转换成URL参数格式(a=1&b=2)
        /// </summary>
        public static string DicToUrlParam(Dictionary<string,string> dic) {
            string paramStr = string.Empty;
 
            foreach (KeyValuePair<string, string> kv in dic)
            {
                paramStr += $"{kv.Key}={kv.Value}";
                paramStr += "&";
            }
            if (!string.IsNullOrWhiteSpace(paramStr)) {
                paramStr = paramStr.Remove(paramStr.Length - 1);
            }
            return paramStr;
        }
        /// <summary>
        /// 将字典按参数名排序转换成URL参数格式(a=1&b=2)
        /// </summary>
        /// <param name="sortType">排序方式</param>
        /// <returns></returns>
        public static string DicToUrlParam(Dictionary<string, string> dic, SortType sortType) {
            if (sortType == SortType.asc) {
                dic = (Dictionary<string, string>)dic.OrderBy(o => o.Key, StringComparer.OrdinalIgnoreCase);
            } else {
                dic = (Dictionary<string, string>)dic.OrderByDescending(o => o.Key, StringComparer.OrdinalIgnoreCase);
            }
            return DicToUrlParam(dic);
        }
 
        /// <summary>
        /// 发送post请求
        /// </summary>
        /// <param name="Url">请求路径</param>
        /// <param name="postDataStr">要提交的参数字符串</param>
        /// <param name="ContentType">ContentType</param>
        /// <returns></returns>
        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;
        }
        /// <summary>
        /// 发送post请求
        /// </summary>
        /// <param name="Url">请求路径</param>
        /// <param name="postDataStr">要提交的参数字符串</param>
        /// <param name="ContentType">ContentType</param>
        /// <returns></returns>
        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();
        }
 
        /// <summary>
        /// 发送post请求
        /// </summary>
        /// <param name="Url">请求路径</param>
        /// <param name="postDataStr">要提交的参数字符串</param>
        /// <param name="headName">携带的头部名</param>
        /// <param name="headValue">携带的头部信息</param>
        /// <returns></returns>
        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;
        }
 
        /// <summary>
        /// 发送含文件的Post请求
        /// </summary>
        /// <param name="url">请求的路径</param>
        /// <param name="postData">发送的参数列表,注意:参数直接写进流里面,需要从MultipartFormDataStreamProvider里面读取,关于Dictionary参数类型,可以json直接转换成Dictionary类型</param>
        /// <param name="files">发送的文件列表<文件名,文件地址></param>
        /// <returns></returns>
        public static string HttpPost(string url, Dictionary<string, string> postData, Dictionary<string, string> 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;
 
        }
 
        /// <summary>
        /// 发送Get请求(返回字符串类型)
        /// </summary>
        /// <param name="Url">请求路径</param>
        /// <returns>返回字符串类型</returns>
        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;
        }
 
        /// <summary>
        /// 发送Get请求(返回一个stream流)
        /// </summary>
        /// <param name="Url">请求路径</param>
        /// <returns>返回一个stream流</returns>
        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();
        }
 
        /// <summary>
        /// 下载资源
        /// </summary>
        /// <param name="url">资源路径</param>
        /// <param name="param">请求参数</param>
        /// <param name="path">资源保存路径(含文件名)</param>
        /// <returns>保存后的路径</returns>
        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;
        }
 
        /// <summary>
        /// 把一个字符串按标识拆分成多个字符串
        /// </summary>
        /// <param name="str">原字符串</param>
        /// <param name="idstr">截断标识</param>
        /// <returns></returns>
        public static List<string> Split(string str, string idstr) {
            List<string> result = new List<string>();
            //传入字符串不能为空
            if (string.IsNullOrEmpty(str)) {
                return new List<string>();
                //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;
        }
 
        /// <summary>
        /// 把一个字符串按标识拆分成多个字符串
        /// </summary>
        /// <param name="str">原字符串</param>
        /// <param name="idstr">截断标识</param>
        /// <param name="isSaveIdstr">是否保留截断标识</param>
        /// <returns></returns>
        public static List<string> Split(string str, string idstr, bool isSaveIdstr)
        {
            if (string.IsNullOrEmpty(str)) {
                return new List<string>();
            }
            if (!isSaveIdstr) {
                return Split(str, idstr);
            }
            List<string> result = new List<string>();
            //传入字符串不能为空
            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;
        }
 
        /// <summary>
        /// 字符串抓取(包含抓取规则中的字符)
        /// </summary>
        /// <param name="str">原始字符串</param>
        /// <param name="rule">抓取的字符串规则,例如ab{*}fg,其中'{*}'是自定义通配符,即后面的wildcard</param>
        /// <param name="wildcard">通配符</param>
        /// <returns>抓取到的字符串列表</returns>
        public static List<string> GrabString(string str, string rule, string wildcard)
        {
            List<string> strs = Helpers.Tool.Split(rule, wildcard, true); //把标识字符串按{*}拆分
            List<string> getStr = new List<string>();//存储抓取到的字符串
            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;
        }
 
        /// <summary>
        /// 字符串抓取
        /// </summary>
        /// <param name="str">原始字符串</param>
        /// <param name="rule">抓取的字符串规则,例如ab{*}fg,其中'{*}'是自定义通配符,即后面的wildcard</param>
        /// <param name="wildcard">通配符</param>
        /// <param name="isGrabRule">是否抓取规则中的字符</param>
        /// <returns>抓取到的字符串列表</returns>
        public static List<string> GrabString(string str, string rule, string wildcard, bool isGrabRule)
        {
            if (isGrabRule) { GrabString(str, rule, wildcard); }
            List<string> strs = Helpers.Tool.Split(rule, wildcard, true); //把标识字符串按{*}拆分
            List<string> getStr = new List<string>();//存储抓取到的字符串
            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;
        }
 
        /// <summary>
        /// 字符串内替换
        /// </summary>
        /// <param name="str">待处理的字符串</param>
        /// <param name="oldStr">要替换的内容</param>
        /// <param name="newStr">替换成的内容</param>
        /// <returns></returns>
        public static string ReplaceString(string str, string oldStr, string newStr) {
            if (string.IsNullOrEmpty(str)) { return ""; }
            string result = "";
            List<string> 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;
        }
        /// <summary>
        /// 获取Core的Json配置
        /// </summary>
        /// <param name="ConfigFileName"></param>
        /// <returns></returns>
        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<SysConfig>();
                return config;
            }
            catch 
            {
                throw new Exception("配置读取错误,请检测项目目录下的appsettings.json文件");
            }
        }
 
        /// <summary>
        /// 检测时间的合法性
        /// </summary>
        /// <param name="t">检测的时间</param>
        /// <returns></returns>
        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; }
        }
 
        /// <summary>
        /// 格式化时间yyyy-MM-dd,失败返回1970-01-01
        /// </summary>
        /// <param name="t"></param>
        /// <returns></returns>
        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");
            }
 
        }
 
        /// <summary>
        /// 取得随机字符
        /// </summary>
        /// <param name="length"></param>
        /// <returns></returns>
        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;
            }
        }
 
        /// <summary>
        /// 删除指定文件
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public static bool DeleteFile(string path) {
            try
            {
                System.IO.File.Delete(path);
                return true;
            }
            catch {
                return false;
            }
        }
 
        /// <summary>
        /// 创建全路径目录
        /// </summary>
        /// <param name="path"></param>
        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, "");  //目录不存在的话创建目录
            }
        }
 
        /// <summary>
        /// 判断传入参数是否为空
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        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;
        }
 
        /// <summary>
        /// 10进制转26进制以字母表示 
        /// </summary>
        /// <param name="number"></param>
        /// <param name="str">传空字符串</param>
        /// <returns></returns>
        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;
            }
        }
    }
 
    /// <summary>
    /// 排序类型
    /// </summary>
    public enum SortType { 
        asc = 1,
        desc = 2,
    }
}