Moli0
2021-12-15 24d68e7998e80cbd4ef3ed04acbf2539a9c5a46b
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
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO.Packaging;
using System.Web;
using System.IO.Compression;
using System.Security.Cryptography;
 
namespace Helpers
{
    public static partial class Tool
    {
        /// <summary>
        /// 文件输出至指定路径
        /// </summary>
        /// <param name="path">文件物理路径,例:C:\test.txt</param>
        /// <param name="content">要输出的内容,以utf-8的格式</param>
        /// <returns>输出结果</returns>
        public static bool PrintTXTFile(string path, string content)
        {
            try
            {
                StreamWriter sw = new StreamWriter(path, false, Encoding.UTF8);
                sw.WriteLine(content);
                sw.Close();
                sw.Dispose();
                return true;
            }
            catch (Exception ex)
            {
                Tool.PrintLog("添加内容失败", ex.Message);
                return false;
            }
        }
 
        /// <summary>
        /// 取得列表类别
        /// </summary>
        /// <param name="number">type</param>
        /// <returns></returns>
        public static string GetType(int number)
        {
            string str = "";
            switch (number)
            {
                case -1: str = "最新添加"; break;
                case 0: str = "学习路上"; break;
                case 1: str = "个人私文"; break;
                case 2: str = "加密"; break;
                case 3: str = "随笔记"; break;
                default: str = ""; break;
            }
            return str;
        }
 
        /// <summary>
        /// 无效字符清空
        /// </summary>
        /// <param name="str">待过滤的字符串</param>
        /// <param name="list">要过滤的字符列表</param>
        /// <returns>过滤掉无效内容后的字符串</returns>
        public static string FilterStr(string str, List<string> list)
        {
            if (string.IsNullOrWhiteSpace(str)) { return ""; }
            foreach (var a in list)
            {
                str = Helpers.Tool.ReplaceString(str, a, "");
            }
            return str;
        }
 
        /// <summary>
        /// 处理html常见标签的字符串
        /// </summary>
        /// <param name="str">待处理的字符串</param>
        /// <returns>处理后的字符串</returns>
        public static string HtmlCodeStr(string str)
        {
            str = Helpers.Tool.ReplaceString(str, "<html>", "");
            str = Helpers.Tool.ReplaceString(str, "</html>", "\f");
            str = Helpers.Tool.ReplaceString(str, "<body>", "");
            str = Helpers.Tool.ReplaceString(str, "</body>", "\n");
            str = Helpers.Tool.ReplaceString(str, "<head>", "");
            str = Helpers.Tool.ReplaceString(str, "</head>", "\n");
            str = Helpers.Tool.ReplaceString(str, "<div>", "");
            str = Helpers.Tool.ReplaceString(str, "</div>", "\n");
            str = Helpers.Tool.ReplaceString(str, "<p>", "\r");
            str = Helpers.Tool.ReplaceString(str, "</p>", "\r");
            str = Helpers.Tool.ReplaceString(str, "<hr>", "\r");
            str = Helpers.Tool.ReplaceString(str, "<a>", "");
            str = Helpers.Tool.ReplaceString(str, "</a>", "");
            str = Helpers.Tool.ReplaceString(str, "<content>", "\n");
            str = Helpers.Tool.ReplaceString(str, "</content>", "\n");
            str = Helpers.Tool.ReplaceString(str, "<iframe>", "\n");
            str = Helpers.Tool.ReplaceString(str, "</iframe>", "\n");
            str = Helpers.Tool.ReplaceString(str, "<h1>", "");
            str = Helpers.Tool.ReplaceString(str, "</h1>", "");
            str = Helpers.Tool.ReplaceString(str, "<h2>", "");
            str = Helpers.Tool.ReplaceString(str, "</h2>", "");
            str = Helpers.Tool.ReplaceString(str, "<h3>", "");
            str = Helpers.Tool.ReplaceString(str, "</h3>", "");
            str = Helpers.Tool.ReplaceString(str, "<h4>", "");
            str = Helpers.Tool.ReplaceString(str, "</h4>", "");
            str = Helpers.Tool.ReplaceString(str, "<i>", "");
            str = Helpers.Tool.ReplaceString(str, "</i>", "");
            str = Helpers.Tool.ReplaceString(str, "&gt;", "<");
            str = Helpers.Tool.ReplaceString(str, "&lt;", ">");
            str = Helpers.Tool.ReplaceString(str, "&nbsp;", " ");
            str = Helpers.Tool.ReplaceString(str, "<br>", "\n\r");
            str = Helpers.Tool.ReplaceString(str, "<br />", "\n\r");
            str = Helpers.Tool.ReplaceString(str, "<Br>", "\n\r");
            str = Helpers.Tool.ReplaceString(str, "<Br />", "\n\r");
            str = Helpers.Tool.ReplaceString(str, "\"", "");
            return str;
        }
 
        /// <summary>
        /// IPV4地址验证
        /// </summary>
        /// <returns></returns>
        public static bool IpAddressSign(string ip)
        {
            try
            {
                if (ip == "::1") { return true; }
                ip = ip.Trim();
                string[] ips = ip.Split('.');
                if (ips.Length != 4) { return false; }
                foreach (var a in ips)
                {
                    int splitAddr = int.Parse(a);
                    if (splitAddr < 0 && splitAddr > 256) { return false; }
                }
                return true;
            }
            catch
            {
                return false;
            }
        }
 
        /// <summary>
        /// 32位大写MD5加密
        /// </summary>
        /// <param name="str">待加密的字符串</param>
        /// <returns></returns>
        public static string MD5(string str)
        {
            string result = MD5(str, true, 32);
            return result;
        }
 
        /// <summary>
        /// 32位MD5加密
        /// </summary>
        /// <param name="str">待加密的字符串</param>
        /// <param name="IsUpper">是否大写</param>
        /// <returns></returns>
        public static string MD5(string str, bool IsUpper)
        {
            string result = MD5(str, IsUpper, 32);
            return result;
        }
 
        /// <summary>
        /// MD5加密
        /// </summary>
        /// <param name="str">待加密的字符串</param>
        /// <param name="IsUpper">是否大写</param>
        /// <param name="bit">加密位数16或者32</param>
        /// <returns></returns>
        public static string MD5(string str, bool IsUpper, int bit)
        {
            System.Security.Cryptography.MD5 md = new System.Security.Cryptography.MD5CryptoServiceProvider();
            byte[] byteStream = System.Text.Encoding.UTF8.GetBytes(str);
            byte[] temp = md.ComputeHash(byteStream);
            StringBuilder tempStr = new StringBuilder();
            string result = null;
            foreach (var a in temp)
            {
                tempStr.Append(a.ToString("x2"));
            }
            if (IsUpper)
            {
                result = tempStr.ToString().ToUpper();
            }
            else
            {
                result = tempStr.ToString().ToLower();
            }
            if (bit == 16)
            {
                result = result.Substring(8, 16);
            }
            else if (bit == 32)
            {
                result = result.ToString();
            }
            else
            {
                result = string.Empty;
            }
            return result;
        }
 
        /// <summary>
        /// Sha256加密
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string Sha256(string str) {
            byte[] bytValue = System.Text.Encoding.UTF8.GetBytes(str);
            SHA256 sha256 = new SHA256CryptoServiceProvider();
 
            byte[] retVal = sha256.ComputeHash(bytValue);
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < retVal.Length; i++)
            {
                sb.Append(retVal[i].ToString("x2"));
            }
            return sb.ToString().ToUpper();
        }
 
        /// <summary>
        /// 验证身份证号格式
        /// </summary>
        /// <param name="code">身份证号</param>
        /// <returns>正确或错误</returns>
        public static bool ValidateIdentityCode(string code)
        {
            if (code.Length != 15 && code.Length != 18) { return false; }
            if (code[0] == 48)
            { return false; }
            foreach (char c in code)
            {
                if (c > 47 && c < 58)
                { continue; }
                else if (c == 88 || c == 120)
                {
                    if (code[17] == c)
                    { continue; }
                    else
                    { return false; }
                }
                else
                { return false; }
            }
            return true;
        }
 
        /// <summary>
        /// 验证手机号格式
        /// </summary>
        /// <param name="mobile">手机号</param>
        /// <returns>正确或错误</returns>
        public static bool ValidateMobile(string mobile)
        {
            if (mobile.Length != 11) { return false; }
            if (mobile[0] != 49) { return false; }
            foreach (char c in mobile)
            {
                if (c < 48 || c > 57)
                {
                    return false;
                }
            }
            return true;
        }
 
        /// <summary>
        /// 验证邮箱格式
        /// </summary>
        /// <param name="mail">邮箱账号</param>
        /// <returns>正确或错误</returns>
        public static bool ValidateMail(string mail)
        {
 
            if (mail.Length < 5) { return false; }
 
            //反转邮箱账号字符串
            string descMail = null;
            foreach (char c in mail.Reverse())
            {
                descMail += c;
            }
 
            int atindex = descMail.IndexOf('@');
            int dotindex = descMail.IndexOf('.');
            if (atindex < 3)
            {
                return false;
            }
            if (dotindex < 1)
            {
                return false;
            }
 
            if (mail[0] == '@' || mail[0] == '.') { return false; }
            if (dotindex > atindex) { return false; }
            return true;
        }
 
        /// <summary>
        /// 过滤非法Sql字符
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string SQLFilter(string str)
        {
            if (string.IsNullOrEmpty(str))
            {
                return "";
            }
            List<string> strs = new List<string>();
            strs.Add("'--");
            strs.Add(";");
            strs.Add("|");
            return FilterStr(str, strs);
        }
 
        /// <summary>
        /// 图片转base64
        /// </summary>
        /// <param name="bmp"></param>
        /// <returns></returns>
        public static string ImgToBase64String(Bitmap bmp)
        {
            try
            {
                MemoryStream ms = new MemoryStream();
                bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                byte[] arr = new byte[ms.Length];
                ms.Position = 0;
                ms.Read(arr, 0, (int)ms.Length);
                ms.Close();
                return Convert.ToBase64String(arr);
            }
            catch
            {
                return null;
            }
        }
 
        /// <summary>
        /// 图片转base64
        /// </summary>
        /// <param name="fs">文件流</param>
        /// <returns></returns>
        public static string ImgToBase64String(FileStream fs) {
            byte[] bytes = new byte[fs.Length];
            fs.Read(bytes, 0, (int)fs.Length);
            string base64Str = Convert.ToBase64String(bytes);
            return base64Str;
        }
 
        /// <summary>
        /// base64保存成图片,返回Bitmap对象
        /// </summary>
        /// <param name="strbase64"></param>
        public static Bitmap Base64StringToImage(string filePath, string fileName, string strbase64, ImageType type)
        {
 
            try
            {
                byte[] arr = Convert.FromBase64String(strbase64);
                MemoryStream ms = new MemoryStream(arr);
                Bitmap bmp = new Bitmap(ms);
 
                switch (type)
                {
                    case ImageType.Jpg: bmp.Save($@"{filePath}\{fileName}.jpg", System.Drawing.Imaging.ImageFormat.Jpeg); break;
                    case ImageType.Bmp: bmp.Save($@"{filePath}\{fileName}.bmp", ImageFormat.Bmp); break;
                    case ImageType.Gif: bmp.Save($@"{filePath}\{fileName}.gif", ImageFormat.Gif); break;
                    case ImageType.Png: bmp.Save($@"{filePath}\{fileName}.png", ImageFormat.Png); break;
                    default: bmp.Save($@"{filePath}\{fileName}.jpg", System.Drawing.Imaging.ImageFormat.Jpeg); break;
                }
                //bmp.Save($@"{savePath}\test.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
                //bmp.Save(@"d:\"test.bmp", ImageFormat.Bmp);
                //bmp.Save(@"d:\"test.gif", ImageFormat.Gif);
                //bmp.Save(@"d:\"test.png", ImageFormat.Png);
                ms.Close();
                return bmp;
            }
            catch (Exception ex)
            {
                Helpers.Tool.PrintLog_Error(ex.Message, ex.StackTrace);
                return null;
            }
        }
 
        /// <summary>
        /// 创建文件夹
        /// </summary>
        /// <param name="filePath">路径</param>
        /// <param name="folderName">文件夹名</param>
        /// <returns></returns>
        public static string CreateDirectory(string filePath, string folderName)
        {
 
            if (string.IsNullOrEmpty(filePath))
            {
                if (string.IsNullOrEmpty(folderName))
                {
                    return "";
                }
            }
            else
            {
                if (filePath.Substring(filePath.Length - 1) == @"\")
                {
                    filePath = filePath.Substring(0, filePath.Length - 1);
                }
            }
            string path = filePath + @"\" + folderName;
            try
            {
                if (!System.IO.Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
            }
            catch (Exception ex)
            {
                Helpers.Tool.PrintLog_Info("出错了!", ex.Message + ex.StackTrace);
                return null;
            }
            Helpers.Tool.PrintLog_Info(path, "");
            return path;
        }
 
        /// <summary>
        /// 将时间转换成秒级的时间戳
        /// </summary>
        /// <param name="time">要转换的时间</param>
        /// <returns></returns>
        public static int DateTimeToDateStr(DateTime time)
        {
            System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
            int timeStr = (int)(DateTime.Now - startTime).TotalSeconds;
            return timeStr;
        }
        /// <summary>
        /// 将时间戳转换成C#的时间
        /// </summary>
        /// <param name="dateStr"></param>
        /// <returns></returns>
        public static DateTime DateStrToDateTime(int dateStr)
        {
            DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
            long lTime = long.Parse(dateStr.ToString() + "0000000");
            TimeSpan toNow = new TimeSpan(lTime);
            return Tool.FormatDate(startTime.Add(toNow));
        }
 
        /// <summary>
        /// 按字典的key升序拼接字典,字典key和value的类型为string
        /// </summary>
        /// <param name="dic"></param>
        /// <returns></returns>
        public static string SplicingDic(Dictionary<string, string> dic)
        {
            if (dic == null)
            {
                return null;
            }
            var temp = dic.OrderBy(o => o.Key, StringComparer.OrdinalIgnoreCase);
            StringBuilder result = new StringBuilder();
            foreach (var a in temp)
            {
                result.Append($"{a.Key}={a.Value}&");
            }
            string str = result.ToString();
            str = str.Substring(0, str.Length - 1);
            return str;
        }
 
        /// <summary>
        /// ASE加密
        /// </summary>
        /// <param name="text">待加密的文本</param>
        /// <param name="key">密钥(可选)</param>
        /// <param name="iv">位移量(可选)</param>
        /// <returns>加密后的密文</returns>
        public static string ASEEncode(string text, string key = "abcd", string iv = "dddd") {
            Helpers.ASEEncryption ase = new Helpers.ASEEncryption();
            return ase.Encrypt(text, key, iv);
        }
 
        /// <summary>
        /// ASE解密
        /// </summary>
        /// <param name="text">密文</param>
        /// <param name="key">密钥(可选)</param>
        /// <param name="iv">位移量(可选)</param>
        /// <returns>解密后的文本</returns>
        public static string ASEDecode(string pwdText, string key = "abcd", string iv = "dddd")
        {
            Helpers.ASEEncryption ase = new Helpers.ASEEncryption();
            return ase.Decrypt(pwdText, key, iv);
        }
 
        /// <summary>
        /// 将指定的文件夹压缩成ZIP文件
        /// </summary>
        /// <param name="folderName">待压缩的文件夹路径</param>
        /// <param name="compressedFileName">压缩后的文件存放路径(含文件名,例C:\test.zip)</param>
        /// <param name="overrideExisting">是否覆盖同名文件</param>
        /// <returns></returns>
        [Obsolete("已弃用,此方法会在压缩包中自动创建了个文件", true)]
        public static bool PackageFolderZIP(string folderName, string compressedFileName, bool overrideExisting)
        {
            if (folderName.EndsWith(@"\"))
                folderName = folderName.Remove(folderName.Length - 1);
            bool result = false;
            if (!Directory.Exists(folderName))
            {
                return result;
            }
 
            if (!overrideExisting && File.Exists(compressedFileName))
            {
                return result;
            }
            try
            {
                using (Package package = Package.Open(compressedFileName, FileMode.Create))
                {
                    var fileList = Directory.EnumerateFiles(folderName, "*", SearchOption.AllDirectories);
                    foreach (string fileName in fileList)
                    {
 
                        //The path in the package is all of the subfolders after folderName
                        string pathInPackage;
                        pathInPackage = Path.GetDirectoryName(fileName).Replace(folderName, string.Empty) + "/" + Path.GetFileName(fileName);
 
                        Uri partUriDocument = PackUriHelper.CreatePartUri(new Uri(pathInPackage, UriKind.Relative));
                        PackagePart packagePartDocument = package.CreatePart(partUriDocument, "", CompressionOption.Maximum);
                        using (FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read))
                        {
                            fileStream.CopyTo(packagePartDocument.GetStream());
                        }
                    }
                }
                result = true;
            }
            catch (Exception e)
            {
                throw new Exception("Error zipping folder " + folderName, e);
            }
 
            return result;
        }
 
        /// <summary>
        /// 解压ZIP文件
        /// </summary>
        /// <param name="folderName">待解压的文件路径</param>
        /// <param name="compressedFileName">解压后存放的目录</param>
        /// <param name="overrideExisting">是否进行覆盖</param>
        /// <returns></returns>
        public static bool UncompressFileZIP(string folderName, string compressedFileName, bool overrideExisting)
        {
            bool result = false;
            try
            {
                if (!File.Exists(compressedFileName))
                {
                    return result;
                }
 
                DirectoryInfo directoryInfo = new DirectoryInfo(folderName);
                if (!directoryInfo.Exists)
                    directoryInfo.Create();
 
                using (Package package = Package.Open(compressedFileName, FileMode.Open, FileAccess.Read))
                {
                    foreach (PackagePart packagePart in package.GetParts())
                    {
                        ExtractPart(packagePart, folderName, overrideExisting);
                    }
                }
 
                result = true;
            }
            catch (Exception e)
            {
                throw new Exception("Error unzipping file " + compressedFileName, e);
            }
 
            return result;
        }
 
        /// <summary>
        /// 将指定的文件夹压缩成ZIP文件
        /// </summary>
        /// <param name="folderName">待压缩的文件夹路径</param>
        /// <param name="compressedFileName">压缩后的文件存放路径(含文件名,例C:\test.zip)</param>
        /// <param name="overrideExisting">是否覆盖同名文件</param>
        /// <returns></returns>
        public static bool ZIPCompressFolder(string folderName, string compressedFileName, bool overrideExisting) {
            if (folderName.EndsWith(@"\"))
                folderName = folderName.Remove(folderName.Length - 1);
            bool result = false;
            if (!Directory.Exists(folderName))
            {
                return result;
            }
 
            if (!overrideExisting && File.Exists(compressedFileName))
            {
                return result;
            }
            if (File.Exists(compressedFileName)) {
                File.Delete(compressedFileName);
            }
            try
            {
                ZipFile.CreateFromDirectory(folderName, compressedFileName);
                return true;
            }
            catch (Exception ex) {
                return false;
            }
        }
 
        /// <summary>
        /// 将多个文件压缩成ZIP文件
        /// </summary>
        /// <param name="fileList">待压缩的文件路径列表</param>
        /// <param name="compressedFileName">压缩后的文件存放路径(含文件名,例C:\test.zip)</param>
        /// <param name="overrideExisting">是否覆盖同名文件</param>
        /// <param name="replaceFolderName">打包后移除的路径部分,示例格式: C:\Files\</param>
        /// <returns></returns>
        public static bool ZIPCompressFiles(List<string> fileList, string compressedFileName, bool overrideExisting,string replaceFolderName = "") {
            bool result = false;
 
            try
            {
                using (Package package = Package.Open(compressedFileName, FileMode.Create))
                {
                    Dictionary<string, int> dic = new Dictionary<string, int>();
                    foreach (string fileName in fileList)
                    {
 
                        if (!File.Exists(fileName)) {
                            return result;
                        }
 
                        //The path in the package is all of the subfolders after folderName
                        string pathInPackage;
                        pathInPackage = Path.GetDirectoryName(fileName).Replace(replaceFolderName, string.Empty) + "/" + Path.GetFileName(fileName);
                        if (dic.ContainsKey(pathInPackage)) {
                            dic[pathInPackage] = dic[pathInPackage]++;
                            int maxLen = Path.GetFileName(fileName).Length;
                            if (Path.GetFileName(fileName).LastIndexOf(".") > -1) {
                                maxLen = Path.GetFileName(fileName).LastIndexOf(".");
                            }
                            pathInPackage = Path.GetFileName(fileName).Substring(0, maxLen) + $"({dic[pathInPackage]})" + Path.GetFileName(fileName).Substring(maxLen);
                        }
                        else {
                            dic.Add(pathInPackage, 0);
                        }
                        Uri partUriDocument = PackUriHelper.CreatePartUri(new Uri(pathInPackage, UriKind.Relative));
                        PackagePart packagePartDocument = package.CreatePart(partUriDocument, "", CompressionOption.Maximum);
                        using (FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read))
                        {
                            fileStream.CopyTo(packagePartDocument.GetStream());
                        }
                    }
                }
                result = true;
            }
            catch (Exception e)
            {
                throw new Exception("Error Directory : " + fileList.ToJson(), e);
            }
            return result;
        }
 
        /// <summary>
        /// 解压ZIP文件
        /// </summary>
        /// <param name="compressedFileName">待解压的文件</param>
        /// <param name="TofolderName">解压后存放的目录</param>
        /// <returns></returns>
        public static bool UnZIPCompressFolder(string compressedFileName, string TofolderName)
        {
            bool result = false;
            if (!File.Exists(compressedFileName)) {
                throw new Exception("未找到相关文件");
            }
            if (TofolderName.EndsWith(@"\")) {
                TofolderName = TofolderName.Remove(TofolderName.Length - 1);
            }
            CreateDirectory(TofolderName, "");
            try
            {
                ZipFile.ExtractToDirectory(compressedFileName, TofolderName);
                return true;
            }
            catch (Exception ex) {
                return false;
            }
 
        }
 
        /// <summary>
        /// 密码加密
        /// </summary>
        /// <param name="account">账号</param>
        /// <param name="pwd">密码</param>
        public static string EncryptPwd(string account, string pwd) {
            return Helpers.Tool.MD5(account + Helpers.Tool.MD5("Moli") + pwd);
        }
 
        /// <summary>
        /// 获取一个新的token
        /// </summary>
        public static string CreateToken(string key) {
            string time = DateTime.Now.ToString("yyyyMMddHHmmssfff");
            string guid = Guid.NewGuid().ToString();
            string param1 = "Moli";
            string param2 = MD5(MD5(time) + Sha256(time) + param1 + Sha256(guid));
 
            string p1 = Sha256(param2);
 
            string token = p1.Insert(Convert.ToInt32(time.Substring(12)) % p1.Length,
                MD5(time).Insert(Convert.ToInt32(time.Substring(12)) % MD5(time).Length, MD5(guid)))
                .Insert(Convert.ToInt32(time.Substring(12)) % p1.Length, Sha256(guid));
            return key + token.Substring(20, token.Length - 30);
        }
 
        /// <summary>
        /// 将文件流的bytes长度转成相应的标准单位
        /// </summary>
        /// <param name="BytesSize">待转的长度,单位bytes</param>
        /// <returns>转换后的标准单位(B,KB,MB,GB,TB)</returns>
        public static string FileSizeChange(long BytesSize) {
            long maxSize = 1024;
            if (BytesSize < 1024) {
                return BytesSize.ToString() + "B";
            } else if (BytesSize < maxSize * maxSize) {
                return Math.Round(Math.Ceiling(BytesSize * 1000 / 1024.00) / 1000.00, 3).ToString() + "KB";
            } else if (BytesSize < maxSize * maxSize * maxSize) {
                return Math.Round(Math.Ceiling(BytesSize * 1000 / (1024.00 * 1024.00)) / 1000.00, 3).ToString() + "MB";
            } else if (BytesSize < maxSize * maxSize * maxSize * maxSize) {
                return Math.Round(Math.Ceiling(BytesSize * 1000 / (1024.00 * 1024.00 * 1024.00)) / 1000.00, 3).ToString() + "GB";
            }
            return Math.Round(Math.Ceiling(BytesSize * 1000 / (1024.00 * 1024.00 * 1024.00) / 1024.00) / 1000.00, 3).ToString() + "TB";
        }
        /// <summary>
        /// 将文件流的bytes长度转成指定的标准单位
        /// </summary>
        /// <param name="BytesSize">待转的长度,单位bytes</param>
        /// <param name="fileSizeUnit">转换后的单位</param>
        /// <returns>转换后的长度(含单位)</returns>
        public static string FileSizeChange(long BytesSize, FileSizeUnit fileSizeUnit) {
            switch (fileSizeUnit) {
                case FileSizeUnit.Bytes: return BytesSize.ToString() + "B";
                case FileSizeUnit.KB: return Math.Round(Math.Ceiling(BytesSize * 1000 / 1024.00) / 1000.00, 3).ToString() + "KB";
                case FileSizeUnit.MB: return Math.Round(Math.Ceiling(BytesSize * 1000 / (1024.00 * 1024.00)) / 1000.00, 3).ToString() + "MB";
                case FileSizeUnit.GB: return Math.Round(Math.Ceiling(BytesSize * 1000 / (1024.00 * 1024.00 * 1024.00)) / 1000.00, 3).ToString() + "GB";
                case FileSizeUnit.TB: return Math.Round(Math.Ceiling(BytesSize * 1000 / (1024.00 * 1024.00 * 1024.00) / 1024.00) / 1000.00, 3).ToString() + "TB";
                default: return FileSizeChange(BytesSize);
            }
        }
 
        /// <summary>
        /// 将带单位的大小换算成以Byte为单位的大小
        /// </summary>
        /// <param name="sizeStr">文件大小,含单位,示例数据:2.31MB</param>
        /// <returns>换算Byte成后的长度</returns>
        public static long FileSizeChangeForByte(string sizeStr) {
            string unit = "";
            long size = 0;
            int index = sizeStr.ToUpper().IndexOf("B");
            if (index == -1) {
                throw new Exception("无效的单位字符");
            }
            if (sizeStr[index - 1] > 71)
            {
                unit = sizeStr.Substring(index - 1);
                size = Convert.ToInt64(sizeStr.Substring(0, index - 1));
            }
            return FileSizeChangeForByte(size, (FileSizeUnit)Enum.Parse(typeof(FileSizeUnit), unit));
        }
        /// <summary>
        /// 将带单位的大小换算成以Byte为单位的大小
        /// </summary>
        /// <param name="size">文件大小,不含单位,示例数据:2.31</param>
        /// <param name="fileSizeUnit">文件大小单位</param>
        /// <returns>换算Byte成后的长度</returns>
        public static long FileSizeChangeForByte(double size, FileSizeUnit fileSizeUnit) {
            switch (fileSizeUnit)
            {
                case FileSizeUnit.Bytes: return Convert.ToInt64(size);
                case FileSizeUnit.KB: return Convert.ToInt64(size*1024);
                case FileSizeUnit.MB: return Convert.ToInt64(size * 1024 * 1024);
                case FileSizeUnit.GB: return Convert.ToInt64(size * 1024 * 1024 * 1024);
                case FileSizeUnit.TB: return Convert.ToInt64(size * 1024 * 1024 * 1024 * 1024);
                default: return Convert.ToInt64(size);
            }
        }
 
        /// <summary>
        /// 将Stream写入FileStream中并返回FileStream
        /// </summary>
        /// <param name="s">Stream对象</param>
        /// <param name="fs">FileStream对象</param>
        /// <returns>写入后的FileStream</returns>
        public static FileStream WriteFileStream(Stream s, FileStream fs) {
            using (BinaryWriter bw = new BinaryWriter(fs)) {
                bw.Write(s.ToByte());
                return fs;
            }
        }
 
        /// <summary>
        /// 路径统一格式化
        /// </summary>
        /// <param name="root">待格式化的路径</param>
        /// <param name="endChar">是否包含路径结束符'\',默认包含</param>
        /// <returns>格式化后的路径</returns>
        public static string GetRoot(string root,bool endChar = true) {
            if (string.IsNullOrWhiteSpace(root)) {
                return "";
            }
 
            if (endChar) {
                if (root.EndsWith("\\"))
                {
                    return root;
                }
                else {
                    root += "\\";
                    return root;
                }
            } else {
                if (root.EndsWith("\\"))
                {
                    root = root.Remove(root.Length - 1);
                    return root;
                }
                else
                {
                    return root;
                }
            }
        }
        /// <summary>
        /// 路径统一格式化
        /// </summary>
        /// <param name="root">待格式化的路径</param>
        /// <param name="fileName">文件名</param>
        /// <returns>格式化后的路径</returns>
        public static string GetRoot(string root, string fileName)
        {
            if (string.IsNullOrWhiteSpace(root))
            {
                return "";
            }
            if (!root.EndsWith("\\"))
            {
                root += "\\";
            }
            root += fileName;
            return root;
        }
 
 
        /// <summary>
        /// 通过完整的文件路径取得Etag
        /// </summary>
        /// <param name="FileName">File Full Name</param>
        /// <returns></returns>
        public static string GetEtag(string FileName) {
            if (!File.Exists(FileName)) {
                throw new Exception("找不到该文件");
            }
            FileInfo fi = new FileInfo(FileName);
            Int64 FileSize = Convert.ToInt64(fi.OpenRead().Length);
            if (FileSize > Int64.MaxValue) {
                throw new Exception("文件过大!");
            }
 
            return GetEtag(fi, FileSize);
        }
 
        /// <summary>
        /// 获取文件的Etag
        /// </summary>
        /// <param name="fi">System.IO.FileInfo</param>
        /// <param name="FileSize">文件Stream.leng</param>
        /// <returns></returns>
        public static string GetEtag(System.IO.FileInfo fi,Int64 FileSize) {
            string Etag = "";
            Etag = MD5("Etag:" + fi.FullName + "----" + fi.LastWriteTimeUtc + "----" + FileSize, true);
            return Etag;
        }
 
        /// <summary>
        /// 检测文件路径中是否含有非法字符
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public static bool ExistsFilePath(string path) {
            string[] s = "\\ : ( ? \" < > |".Split(" ");
            foreach (string a in s) {
                if (path.IndexOf(a) > -1) {
                    return false;
                }
            }
            return true;
        }
 
        private static void ExtractPart(PackagePart packagePart, string targetDirectory, bool overrideExisting)
        {
            string stringPart = targetDirectory + HttpUtility.UrlDecode(packagePart.Uri.ToString()).Replace('\\', '/');
 
            if (!Directory.Exists(Path.GetDirectoryName(stringPart)))
                Directory.CreateDirectory(Path.GetDirectoryName(stringPart));
 
            if (!overrideExisting && File.Exists(stringPart))
                return;
            using (FileStream fileStream = new FileStream(stringPart, FileMode.Create))
            {
                packagePart.GetStream().CopyTo(fileStream);
            }
        }
    }
 
    /// <summary>
    /// 枚举图片格式
    /// </summary>
    public enum ImageType {
        Jpg = 0,
        Bmp = 1,
        Gif = 2,
        Png = 3
    }
 
    public enum FileSizeUnit {
        bit = 0,
        Bytes = 1,
        KB = 2,
        MB = 3,
        GB = 4,
        TB = 5,
    }
}