欢迎莅临 SUN WU GANG 的园子!!!

世上无难事,只畏有心人。有心之人,即立志之坚午也,志坚则不畏事之不成。

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::
  470 随笔 :: 0 文章 :: 22 评论 :: 30万 阅读
< 2025年3月 >
23 24 25 26 27 28 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 1 2 3 4 5

实现方式/思路:FTP文件(应用程序包)下载,解压

帮助类:

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
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
 
namespace AutoUpdate.Helper
{
    public class ProcessHelper
    {
        private static ProcessHelper instance;
        public static ProcessHelper Instance
        {
            get
            {
                if (instance == null) instance = new ProcessHelper();
                return ProcessHelper.instance;
            }
        }
 
        /// <summary>
        /// 关闭进程
        /// </summary>
        /// <param name="processName">进程名</param>
        public void KillProcessByName(string processName)
        {
            try
            {
                Process[] myproc = Process.GetProcesses();
                foreach (Process item in myproc)
                {
                    if (item.ProcessName == processName)
                    {
                        item.CloseMainWindow();
                        item.Kill();
                    }
                }
            }
            catch { return; }
        }
 
        /// <summary>
        /// 启动进程
        /// </summary>
        /// <param name="processName">进程名,完全限定名</param>
        public void StartProcessByName(string processName)
        {
            System.Diagnostics.Process.Start(processName);
            //Process process = new Process();//声明一个进程类对象
            //process.StartInfo.FileName = processName;//Application.StartupPath + "\\AutoUpdate.exe";
            //process.Start();
        }
 
        public void StartProcessByName(string processName,string param)
        {
            //System.Diagnostics.Process.Start(processName);
            Process p = new Process();//声明一个进程类对象
            p.StartInfo.FileName = processName;// Application.StartupPath + "\\AutoUpdate.exe";
            p.StartInfo.UseShellExecute = true;
            p.StartInfo.Arguments = param;
            p.Start();
        }
 
 
    }
}
 
using System;
using System.IO;
using System.Diagnostics;
using Microsoft.Win32;
using ICSharpCode.SharpZipLib.Checksums;
using ICSharpCode.SharpZipLib.Zip;
 
namespace AutoUpdate.Helper
{
    public class SharpZip
    {
        public SharpZip()
        { }
 
        /// <summary>
        /// 压缩
        /// </summary>
        /// <param name="filename"> 压缩后的文件名(包含物理路径)</param>
        /// <param name="directory">待压缩的文件夹(包含物理路径)</param>
        public static void PackFiles(string filename, string directory)
        {
            try
            {
                FastZip fz = new FastZip();
                fz.CreateEmptyDirectories = true;
                fz.CreateZip(filename, directory, true, "");
                fz = null;
            }
            catch (Exception)
            {
                throw;
            }
        }
 
        /// <summary>
        /// 解压缩
        /// </summary>
        /// <param name="file">待解压文件名(包含物理路径)</param>
        /// <param name="targetdir"> 解压到哪个目录中(包含物理路径)</param>
        public static bool UnpackFiles(string file, string targetdir)
        {
            try
            {
                if (!Directory.Exists(targetdir))
                {
                    Directory.CreateDirectory(targetdir);
                }
                ZipInputStream s = new ZipInputStream(File.OpenRead(file));
                ZipEntry theEntry;
                while ((theEntry = s.GetNextEntry()) != null)
                {
                    string directoryName = Path.GetDirectoryName(theEntry.Name);
                    string fileName = Path.GetFileName(theEntry.Name);
                    if (directoryName != String.Empty)
                    {
                        Directory.CreateDirectory(targetdir + directoryName);
                    }
                    if (fileName != String.Empty)
                    {
                        //FileStream streamWriter = File.Create(targetdir + theEntry.Name);
                        FileStream streamWriter = File.Create(theEntry.Name);
                        int size = 2048;
                        byte[] data = new byte[2048];
                        while (true)
                        {
                            size = s.Read(data, 0, data.Length);
                            if (size > 0)
                            {
                                streamWriter.Write(data, 0, size);
                            }
                            else
                            {
                                break;
                            }
                        }
                        streamWriter.Close();
                    }
                }
                s.Close();
                return true;
            }
            catch (Exception)
            {
                throw;
            }
        }
    }
 
    public class ClassZip
    {
        #region 私有方法
        /// <summary>
        /// 递归压缩文件夹方法
        /// </summary>
        private static bool ZipFileDictory(string FolderToZip, ZipOutputStream s, string ParentFolderName)
        {
            bool res = true;
            string[] folders, filenames;
            ZipEntry entry = null;
            FileStream fs = null;
            Crc32 crc = new Crc32();
            try
            {
                entry = new ZipEntry(Path.Combine(ParentFolderName, Path.GetFileName(FolderToZip) + "/"));
                s.PutNextEntry(entry);
                s.Flush();
                filenames = Directory.GetFiles(FolderToZip);
                foreach (string file in filenames)
                {
                    fs = File.OpenRead(file);
                    byte[] buffer = new byte[fs.Length];
                    fs.Read(buffer, 0, buffer.Length);
                    entry = new ZipEntry(Path.Combine(ParentFolderName, Path.GetFileName(FolderToZip) + "/" + Path.GetFileName(file)));
                    entry.DateTime = DateTime.Now;
                    entry.Size = fs.Length;
                    fs.Close();
                    crc.Reset();
                    crc.Update(buffer);
                    entry.Crc = crc.Value;
                    s.PutNextEntry(entry);
                    s.Write(buffer, 0, buffer.Length);
                }
            }
            catch
            {
                res = false;
            }
            finally
            {
                if (fs != null)
                {
                    fs.Close();
                    fs = null;
                }
                if (entry != null)
                {
                    entry = null;
                }
                GC.Collect();
                GC.Collect(1);
            }
            folders = Directory.GetDirectories(FolderToZip);
            foreach (string folder in folders)
            {
                if (!ZipFileDictory(folder, s, Path.Combine(ParentFolderName, Path.GetFileName(FolderToZip))))
                {
                    return false;
                }
            }
            return res;
        }
 
        /// <summary>
        /// 压缩目录
        /// </summary>
        /// <param name="FolderToZip">待压缩的文件夹,全路径格式</param>
        /// <param name="ZipedFile">压缩后的文件名,全路径格式</param>
        private static bool ZipFileDictory(string FolderToZip, string ZipedFile, int level)
        {
            bool res;
            if (!Directory.Exists(FolderToZip))
            {
                return false;
            }
            ZipOutputStream s = new ZipOutputStream(File.Create(ZipedFile));
            s.SetLevel(level);
            res = ZipFileDictory(FolderToZip, s, "");
            s.Finish();
            s.Close();
            return res;
        }
 
        /// <summary>
        /// 压缩文件
        /// </summary>
        /// <param name="FileToZip">要进行压缩的文件名</param>
        /// <param name="ZipedFile">压缩后生成的压缩文件名</param>
        private static bool ZipFile(string FileToZip, string ZipedFile, int level)
        {
            if (!File.Exists(FileToZip))
            {
                throw new System.IO.FileNotFoundException("指定要压缩的文件: " + FileToZip + " 不存在!");
            }
            FileStream ZipFile = null;
            ZipOutputStream ZipStream = null;
            ZipEntry ZipEntry = null;
            bool res = true;
            try
            {
                ZipFile = File.OpenRead(FileToZip);
                byte[] buffer = new byte[ZipFile.Length];
                ZipFile.Read(buffer, 0, buffer.Length);
                ZipFile.Close();
 
                ZipFile = File.Create(ZipedFile);
                ZipStream = new ZipOutputStream(ZipFile);
                ZipEntry = new ZipEntry(Path.GetFileName(FileToZip));
                ZipStream.PutNextEntry(ZipEntry);
                ZipStream.SetLevel(level);
 
                ZipStream.Write(buffer, 0, buffer.Length);
            }
            catch
            {
                res = false;
            }
            finally
            {
                if (ZipEntry != null)
                {
                    ZipEntry = null;
                }
                if (ZipStream != null)
                {
                    ZipStream.Finish();
                    ZipStream.Close();
                }
                if (ZipFile != null)
                {
                    ZipFile.Close();
                    ZipFile = null;
                }
                GC.Collect();
                GC.Collect(1);
            }
            return res;
        }
        #endregion
 
        /// <summary>
        /// 压缩
        /// </summary>
        /// <param name="FileToZip">待压缩的文件目录</param>
        /// <param name="ZipedFile">生成的目标文件</param>
        /// <param name="level">6</param>
        public static bool Zip(String FileToZip, String ZipedFile, int level)
        {
            if (Directory.Exists(FileToZip))
            {
                return ZipFileDictory(FileToZip, ZipedFile, level);
            }
            else if (File.Exists(FileToZip))
            {
                return ZipFile(FileToZip, ZipedFile, level);
            }
            else
            {
                return false;
            }
        }
 
        /// <summary>
        /// 解压
        /// </summary>
        /// <param name="FileToUpZip">待解压的文件</param>
        /// <param name="ZipedFolder">解压目标存放目录</param>
        public static void UnZip(string FileToUpZip, string ZipedFolder)
        {
            if (!File.Exists(FileToUpZip))
            {
                return;
            }
            if (!Directory.Exists(ZipedFolder))
            {
                Directory.CreateDirectory(ZipedFolder);
            }
            ZipInputStream s = null;
            ZipEntry theEntry = null;
            string fileName;
            FileStream streamWriter = null;
            try
            {
                s = new ZipInputStream(File.OpenRead(FileToUpZip));
                while ((theEntry = s.GetNextEntry()) != null)
                {
                    if (theEntry.Name != String.Empty)
                    {
                        fileName = Path.Combine(ZipedFolder, theEntry.Name);
                        if (fileName.EndsWith("/") || fileName.EndsWith("\\"))
                        {
                            Directory.CreateDirectory(fileName);
                            continue;
                        }
                        streamWriter = File.Create(fileName);
                        int size = 2048;
                        byte[] data = new byte[2048];
                        while (true)
                        {
                            size = s.Read(data, 0, data.Length);
                            if (size > 0)
                            {
                                streamWriter.Write(data, 0, size);
                            }
                            else
                            {
                                break;
                            }
                        }
                    }
                }
            }
            finally
            {
                if (streamWriter != null)
                {
                    streamWriter.Close();
                    streamWriter = null;
                }
                if (theEntry != null)
                {
                    theEntry = null;
                }
                if (s != null)
                {
                    s.Close();
                    s = null;
                }
                GC.Collect();
                GC.Collect(1);
            }
        }
    }
 
    public class ZipHelper
    {
        #region 私有变量
        String the_rar;
        RegistryKey the_Reg;
        Object the_Obj;
        String the_Info;
        ProcessStartInfo the_StartInfo;
        Process the_Process;
        #endregion
 
        /// <summary>
        /// 压缩
        /// </summary>
        /// <param name="zipname">要解压的文件名</param>
        /// <param name="zippath">要压缩的文件目录</param>
        /// <param name="dirpath">初始目录</param>
        public void EnZip(string zipname, string zippath, string dirpath)
        {
            try
            {
                the_Reg = Registry.ClassesRoot.OpenSubKey(@"Applications\WinRAR.exe\Shell\Open\Command");
                the_Obj = the_Reg.GetValue("");
                the_rar = the_Obj.ToString();
                the_Reg.Close();
                the_rar = the_rar.Substring(1, the_rar.Length - 7);
                the_Info = " a    " + zipname + "  " + zippath;
                the_StartInfo = new ProcessStartInfo();
                the_StartInfo.FileName = the_rar;
                the_StartInfo.Arguments = the_Info;
                the_StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
                the_StartInfo.WorkingDirectory = dirpath;
                the_Process = new Process();
                the_Process.StartInfo = the_StartInfo;
                the_Process.Start();
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
 
        /// <summary>
        /// 解压缩
        /// </summary>
        /// <param name="zipname">要解压的文件名</param>
        /// <param name="zippath">要解压的文件路径</param>
        public void DeZip(string zipname, string zippath)
        {
            try
            {
                the_Reg = Registry.ClassesRoot.OpenSubKey(@"Applications\WinRar.exe\Shell\Open\Command");
                the_Obj = the_Reg.GetValue("");
                the_rar = the_Obj.ToString();
                the_Reg.Close();
                the_rar = the_rar.Substring(1, the_rar.Length - 7);
                the_Info = " X " + zipname + " " + zippath;
                the_StartInfo = new ProcessStartInfo();
                the_StartInfo.FileName = the_rar;
                the_StartInfo.Arguments = the_Info;
                the_StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
                the_Process = new Process();
                the_Process.StartInfo = the_StartInfo;
                the_Process.Start();
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
    }
 
}
 
 
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Net;
using System.Text;
using System.Windows.Forms;
 
namespace AutoUpdate.Helper
{
    public class UpdateHelper
    {
        private static UpdateHelper instance;
        public static UpdateHelper Instance
        {
            get
            {
                if (instance == null) instance = new UpdateHelper();
                return UpdateHelper.instance;
            }
        }
 
        //基本设置
        private string FTPFilePath = @"ftp://" + ConfigurationManager.AppSettings["FTPFilePath"];    //目标路径
        private string FtpServerPort = ConfigurationManager.AppSettings["FtpServerPort"];    //ftp IP地址
        private string FtpServerIP = ConfigurationManager.AppSettings["FtpServerIP"];    //ftp IP地址
        private string FtpServerUserName = ConfigurationManager.AppSettings["FtpServerUserName"];   //ftp用户名
        private string FtpServerPassword = ConfigurationManager.AppSettings["FtpServerPassword"];   //ftp密码
 
        //获取ftp上面的文件和文件夹
        public string[] GetFileList(string dir)
        {
            string[] downloadFiles;
            StringBuilder result = new StringBuilder();
            FtpWebRequest request;
            try
            {
                request = (FtpWebRequest)FtpWebRequest.Create(new Uri(FTPFilePath));
                request.UseBinary = true;
                request.Credentials = new NetworkCredential(FtpServerUserName, FtpServerPassword);//设置用户名和密码
                request.Method = WebRequestMethods.Ftp.ListDirectory;
                request.UseBinary = true;
 
                WebResponse response = request.GetResponse();
                StreamReader reader = new StreamReader(response.GetResponseStream());
                string line = reader.ReadLine();
                while (line != null)
                {
                    result.Append(line);
                    result.Append("\n");
                    Console.WriteLine(line);
                    line = reader.ReadLine();
                }
                // to remove the trailing '\n'
                result.Remove(result.ToString().LastIndexOf('\n'), 1);
                reader.Close();
                response.Close();
                return result.ToString().Split('\n');
            }
            catch (Exception ex)
            {
                Console.WriteLine("获取ftp上面的文件和文件夹:" + ex.Message);
                downloadFiles = null;
                return downloadFiles;
            }
        }
 
        /// <summary>
        /// 获取文件大小
        /// </summary>
        /// <param name="file">ip服务器下的相对路径</param>
        /// <returns>文件大小</returns>
        public int GetFileSize(string file)
        {
            StringBuilder result = new StringBuilder();
            FtpWebRequest request;
            try
            {
                request = (FtpWebRequest)FtpWebRequest.Create(new Uri(FTPFilePath + file));
                request.UseBinary = true;
                request.Credentials = new NetworkCredential(FtpServerUserName, FtpServerPassword);//设置用户名和密码
                request.Method = WebRequestMethods.Ftp.GetFileSize;
 
                return (int)request.GetResponse().ContentLength;
            }
            catch (Exception ex)
            {
                Console.WriteLine("获取文件大小出错:" + ex.Message);
                return -1;
            }
        }
 
        /// <summary>
        /// 文件上传
        /// </summary>
        /// <param name="filePath">原路径(绝对路径)包括文件名</param>
        /// <param name="objPath">目标文件夹:服务器下的相对路径 不填为根目录</param>
        public void FileUpLoad(string filePath, string objPath = "")
        {
            try
            {
                string url = FTPFilePath;
                if (objPath != "") url += objPath + "/";
                try
                {
 
                    FtpWebRequest reqFTP = null;
                    //待上传的文件 (全路径)
                    try
                    {
                        FileInfo fileInfo = new FileInfo(filePath);
                        using (FileStream fs = fileInfo.OpenRead())
                        {
                            long length = fs.Length;
                            reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(url + fileInfo.Name));
                            //设置连接到FTP的帐号密码
                            reqFTP.Credentials = new NetworkCredential(FtpServerUserName, FtpServerPassword);
                            //设置请求完成后是否保持连接
                            reqFTP.KeepAlive = false;
                            //指定执行命令
                            reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
                            //指定数据传输类型
                            reqFTP.UseBinary = true;
 
                            using (Stream stream = reqFTP.GetRequestStream())
                            {
                                //设置缓冲大小
                                int BufferLength = 5120;
                                byte[] b = new byte[BufferLength];
                                int i;
                                while ((i = fs.Read(b, 0, BufferLength)) > 0)
                                {
                                    stream.Write(b, 0, i);
                                }
                                Console.WriteLine("上传文件成功");
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("上传文件失败错误为" + ex.Message);
                    }
                    finally
                    {
 
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("上传文件失败错误为" + ex.Message);
                }
                finally
                {
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("上传文件失败错误为" + ex.Message);
            }
        }
 
        /// <summary>
        /// 删除文件
        /// </summary>
        /// <param name="fileName">服务器下的相对路径 包括文件名</param>
        public void DeleteFileName(string fileName)
        {
            try
            {
                FileInfo fileInf = new FileInfo(FtpServerIP + "" + fileName);
                string uri = FTPFilePath + fileName;
                FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
                // 指定数据传输类型
                reqFTP.UseBinary = true;
                // ftp用户名和密码
                reqFTP.Credentials = new NetworkCredential(FtpServerUserName, FtpServerPassword);
                // 默认为true,连接不会被关闭
                // 在一个命令之后被执行
                reqFTP.KeepAlive = false;
                // 指定执行什么命令
                reqFTP.Method = WebRequestMethods.Ftp.DeleteFile;
                FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                response.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine("删除文件出错:" + ex.Message);
            }
        }
 
        /// <summary>
        /// 新建目录 上一级必须先存在
        /// </summary>
        /// <param name="dirName">服务器下的相对路径</param>
        public void MakeDir(string dirName)
        {
            try
            {
                string uri = FTPFilePath + dirName;
                FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
                // 指定数据传输类型
                reqFTP.UseBinary = true;
                // ftp用户名和密码
                reqFTP.Credentials = new NetworkCredential(FtpServerUserName, FtpServerPassword);
                reqFTP.Method = WebRequestMethods.Ftp.MakeDirectory;
                FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                response.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine("创建目录出错:" + ex.Message);
            }
        }
 
        /// <summary>
        /// 删除目录 上一级必须先存在
        /// </summary>
        /// <param name="dirName">服务器下的相对路径</param>
        public void DelDir(string dirName)
        {
            try
            {
                string uri = FTPFilePath + dirName;
                FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
                // ftp用户名和密码
                reqFTP.Credentials = new NetworkCredential(FtpServerUserName, FtpServerPassword);
                reqFTP.Method = WebRequestMethods.Ftp.RemoveDirectory;
                FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                response.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine("删除目录出错:" + ex.Message);
            }
        }
 
        /// <summary>
        /// 从ftp服务器上获得文件夹列表
        /// </summary>
        /// <param name="RequedstPath">服务器下的相对路径</param>
        /// <returns></returns>
        public List<string> GetDirctory(string RequedstPath)
        {
            List<string> strs = new List<string>();
            try
            {
                string uri = FTPFilePath + RequedstPath;   //目标路径 path为服务器地址
                FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
                // ftp用户名和密码
                reqFTP.Credentials = new NetworkCredential(FtpServerUserName, FtpServerPassword);
                reqFTP.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
                WebResponse response = reqFTP.GetResponse();
                StreamReader reader = new StreamReader(response.GetResponseStream());//中文文件名
 
                string line = reader.ReadLine();
                while (line != null)
                {
                    if (line.Contains("<DIR>"))
                    {
                        string msg = line.Substring(line.LastIndexOf("<DIR>") + 5).Trim();
                        strs.Add(msg);
                    }
                    line = reader.ReadLine();
                }
                reader.Close();
                response.Close();
                return strs;
            }
            catch (Exception ex)
            {
                Console.WriteLine("获取目录出错:" + ex.Message);
            }
            return strs;
        }
 
        /// <summary>
        /// 从ftp服务器上获得文件列表
        /// </summary>
        /// <param name="RequedstPath">服务器下的相对路径</param>
        /// <returns></returns>
        public List<string> GetFile(string RequedstPath)
        {
            List<string> strs = new List<string>();
            try
            {
                string uri = FTPFilePath + RequedstPath;   //目标路径 path为服务器地址
                FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
                // ftp用户名和密码
                reqFTP.Credentials = new NetworkCredential(FtpServerUserName, FtpServerPassword);
                reqFTP.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
                WebResponse response = reqFTP.GetResponse();
                StreamReader reader = new StreamReader(response.GetResponseStream());//中文文件名
 
                string line = reader.ReadLine();
                while (line != null)
                {
                    if (!line.Contains("<DIR>"))
                    {
                        string msg = line.Substring(39).Trim();
                        strs.Add(msg);
                    }
                    line = reader.ReadLine();
                }
                reader.Close();
                response.Close();
                return strs;
            }
            catch (Exception ex)
            {
                Console.WriteLine("获取文件出错:" + ex.Message);
            }
            return strs;
        }
 
        /// <summary>
        /// 从ftp服务器上下载文件的功能 
        /// </summary>
        /// <param name="fileName">文件名称</param>
        public void Download(string fileName)
        {
            FtpWebRequest reqFTP;
            try
            {
                string filePath = Application.StartupPath;
                FileStream outputStream = new FileStream(filePath + "\\" + fileName, FileMode.Create);
                string str = FTPFilePath + ":" + FtpServerPort + "/" + fileName;
                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(str));
                reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
                reqFTP.UseBinary = true;
                reqFTP.Credentials = new NetworkCredential(FtpServerUserName, FtpServerPassword);
                reqFTP.UsePassive = false;
                FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                Stream ftpStream = response.GetResponseStream();
                long cl = response.ContentLength;
                int bufferSize = 2048;
                int readCount;
                byte[] buffer = new byte[bufferSize];
                readCount = ftpStream.Read(buffer, 0, bufferSize);
                while (readCount > 0)
                {
                    outputStream.Write(buffer, 0, readCount);
                    readCount = ftpStream.Read(buffer, 0, bufferSize);
                }
                ftpStream.Close();
                outputStream.Close();
                response.Close();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
 
        /// <summary>
        /// 解压文件
        /// </summary>
        /// <param name="fileName">文件名</param>
        /// <param name="initPath">路径(不含文件名)</param>
        public void DownloadDir(string fileName,string initPath)
        {
            FtpWebRequest reqFTP;
            try
            {
                string filePath = initPath;// Application.StartupPath;
                FileStream outputStream = new FileStream(filePath + "\\" + fileName, FileMode.Create);
                string str = FTPFilePath + ":" + FtpServerPort + "/" + fileName;
                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(str));
                reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
                reqFTP.UseBinary = true;
                reqFTP.Credentials = new NetworkCredential(FtpServerUserName, FtpServerPassword);
                reqFTP.UsePassive = false;
                FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                Stream ftpStream = response.GetResponseStream();
                long cl = response.ContentLength;
                int bufferSize = 2048;
                int readCount;
                byte[] buffer = new byte[bufferSize];
                readCount = ftpStream.Read(buffer, 0, bufferSize);
                while (readCount > 0)
                {
                    outputStream.Write(buffer, 0, readCount);
                    readCount = ftpStream.Read(buffer, 0, bufferSize);
                }
                ftpStream.Close();
                outputStream.Close();
                response.Close();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
 
        /// <summary>
        /// 从ftp服务器上下载文件的功能 
        /// </summary>
        /// <param name="fileName">文件名称</param>
        /// <param name="targetPath">存放目标位置+文件名称</param>
        public void Download(string fileName, string targetPath)
        {
            FtpWebRequest reqFTP;
            try
            {
                string filePath = Application.StartupPath;
                //FileStream outputStream = new FileStream(filePath + "\\" + fileName, FileMode.Create);
                FileStream outputStream = new FileStream(targetPath, FileMode.Create);
                string str = FTPFilePath + ":" + FtpServerPort + "/" + fileName;
                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(str));
                reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
                reqFTP.UseBinary = true;
                reqFTP.Credentials = new NetworkCredential(FtpServerUserName, FtpServerPassword);
                reqFTP.UsePassive = false;
                FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                Stream ftpStream = response.GetResponseStream();
                long cl = response.ContentLength;
                int bufferSize = 2048;
                int readCount;
                byte[] buffer = new byte[bufferSize];
                readCount = ftpStream.Read(buffer, 0, bufferSize);
                while (readCount > 0)
                {
                    outputStream.Write(buffer, 0, readCount);
                    readCount = ftpStream.Read(buffer, 0, bufferSize);
                }
                ftpStream.Close();
                outputStream.Close();
                response.Close();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
 
        /// <summary>
        /// 用FTP方式上传文件
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="uploadUrl"></param>
        /// <param name="msg"></param>
        public void Upload(string fileName, string uploadUrl)
        {
            Stream requestStream = null;
            FileStream fileStream = null;
            FtpWebResponse response = null; try
            {
                FtpWebRequest request = (FtpWebRequest)WebRequest.Create(uploadUrl);
                request.Method = WebRequestMethods.Ftp.UploadFile;
                request.Credentials = new NetworkCredential(FtpServerUserName, FtpServerPassword);
                request.Proxy = null;
                requestStream = request.GetRequestStream();
                fileStream = File.Open(fileName, FileMode.Open);
                byte[] buffer = new byte[1024];
                int bytesRead;
                while (true)
                {
                    bytesRead = fileStream.Read(buffer, 0, buffer.Length);
                    if (bytesRead == 0) break;
 
                    requestStream.Write(buffer, 0, bytesRead);
                }
                requestStream.Close();
                response = (FtpWebResponse)request.GetResponse();
            }
            catch (UriFormatException ex)
            {
 
            }
            catch (IOException ex)
            {
 
            }
            catch (WebException ex)
            {
 
            }
            finally
            {
                if (response != null) response.Close();
                if (fileStream != null) fileStream.Close();
                if (requestStream != null) requestStream.Close();
            }
        }
    }
}
 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace AutoUpdate.Helper
{
    public class VarHelper
    {
        private static VarHelper instance;
        public static VarHelper Instance
        {
            get
            {
                if (instance == null) instance = new VarHelper();
                return VarHelper.instance;
            }
        }
 
        //初始路径 + 自动更新程序名称 + 主程序名称
        //string param = fullPath + ","
        //    + "AutoUpdate\\AutoUpdate.exe," //自动更新程序
        //    + "Debug\\AutoUpdateApp.exe,"//主程序
        //    + "Debug";//下载包
        /// <summary>
        /// 需要更新的文件夹  初始路径
        /// </summary>
        public string InitPath = "";
        /// <summary>
        /// 自动更新程序名称
        /// </summary>
        public string AutoUpdateExe = "";
        /// <summary>
        /// 主程序名称
        /// </summary>
        public string MainExe = "";
        /// <summary>
        /// 下载包
        /// </summary>
        public string DownDir = "";
    }
}

自动更新程序:

 

 

 

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
using AutoUpdate.Helper;
using System;
using System.Collections.Generic;
using System.IO;
using System.Windows.Forms;
using ZB.QueueSys.Common;
 
namespace AutoUpdate
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
        }
 
        private void MainForm_Load(object sender, EventArgs e)
        {
            UpdateApp();
        }
 
        private void UpdateApp()
        {
            this.probarWatting.Style = ProgressBarStyle.Marquee;
            this.probarWatting.Show();
 
            try
            {
                #region 注释代码
                //NewMethod();
 
                //    DirectoryInfo di = new DirectoryInfo(string.Format(@"{0}..\..\", Application.StartupPath));
                //    string fullPath = di.FullName;
                //    string param = fullPath + ","
                //+ "AutoUpdate\\AutoUpdate.exe," //自动更新程序
                //+ "Debug\\AutoUpdateApp.exe,"//主程序
                //+ "Debug";//下载包
 
                //    VarHelper.Instance.InitPath = param[0];
                //    VarHelper.Instance.AutoUpdateExe = param[1];
                //    VarHelper.Instance.MainExe = param[2];
                //    VarHelper.Instance.DownDir = param[3];
                #endregion
 
                string fileZip = VarHelper.Instance.InitPath + VarHelper.Instance.DownDir;//+ "\\QueueSys.zip";
                string target = VarHelper.Instance.InitPath + "\\" + VarHelper.Instance.DownDir;
 
                UpdateHelper.Instance.DownloadDir(VarHelper.Instance.DownDir + ".zip", VarHelper.Instance.InitPath);//需要下载的压缩文件名称
                //从那解压到哪
                SharpZip.UnpackFiles(fileZip + ".zip", target);//MessageBox.Show("解压target==" + target);  //ClassZip.UnZip(fileZip + ".zip", target);
                DialogResult result = MessageBox.Show("更新已完成,是否启动预约程序?", "提示",
                    MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
                if (result.Equals(DialogResult.OK))
                {
                    File.Delete(fileZip + ".zip");//MessageBox.Show("开始删除临时压缩文件" + fileZip + ".zip");
 
                    string mainExe = VarHelper.Instance.InitPath + VarHelper.Instance.MainExe;//"\\QueueSys";
                    ProcessHelper.Instance.StartProcessByName(mainExe);                    //MessageBox.Show("启动==" + mainExe);
                    ProcessHelper.Instance.KillProcessByName("AutoUpdate");
                    //System.GC.Collect();//垃圾回收
                }
 
            }
            catch (Exception ex)
            {
                //MessageBox.Show("删除压缩文件==" + ex.Message + ex.StackTrace);
                MessageBox.Show("更新失败,请联系管理员");
                LogHelper.Instance.SaveText("" + ex.Message + ex.StackTrace);
                return;
            }
        }
 
        private void NewMethod()
        {
            // 第一步下载需要更新的配置文件
            string filepath = "UpdateList.xml";
            UpdateHelper.Instance.Download(filepath);
            // 第二步 提供并解析配置文件(获取需要更新的文件名称、文件更新后的路径)
            string path = Application.StartupPath + "\\UpdateList.xml";
            List<UpdateList> list = AutoUpdate.Helper.XmlHelper.Instance.GetUpdateList(path, "Root");
            //第三步 循环下载文件到指定路径
            foreach (UpdateList item in list)
            {
                if (string.IsNullOrEmpty(item.PATH)) UpdateHelper.Instance.Download(item.NAME);//下载至根目录
                else //下载至指定目录
                {
                    string targetPath = Application.StartupPath + "\\" + item.PATH + "\\" + item.NAME;
                    UpdateHelper.Instance.Download(item.NAME, targetPath);
                }
            }
        }
 
        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            DialogResult result = MessageBox.Show("程序正在更新,退出将导致异常", "是否确认退出",
                MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
            if (result.Equals(DialogResult.OK))
            {
                Application.Exit();
            }
        }
 
        private void buttonTest_Click(object sender, EventArgs e)
        {
            UpdateApp();
        }
 
 
    }
}<br><br> 主程序:using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
 
namespace AutoUpdateApp
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
 
        private void button1_Click(object sender, EventArgs e)
        {
            DirectoryInfo info = new DirectoryInfo(Application.StartupPath);
            string path = info.Parent.Parent.FullName;
 
            DirectoryInfo di = new DirectoryInfo(string.Format(@"{0}..\..\", Application.StartupPath));
            string fullPath = di.FullName;
 
            //初始路径 + 自动更新程序名称 + 主程序名称
            string param = fullPath + ","
                + "AutoUpdate\\AutoUpdate.exe," //自动更新程序
                + "Debug\\AutoUpdateApp.exe,"//主程序
                + "Debug";//下载包
 
            //AutoUpdate
            Process p = new Process();//声明一个进程类对象
            p.StartInfo.FileName = fullPath + "AutoUpdate\\AutoUpdate.exe";
            p.StartInfo.UseShellExecute = true;
            p.StartInfo.Arguments = param;//第一个参数为需要下载的压缩文件,第二个为需要启动的程序
            p.Start();
 
            //关闭当期
            //Process[] p_arry = Process.GetProcesses();//得到系统所有进程
            //for (int i = 0; i < p_arry.Length; i++)//遍历每个进程
            //{
            //    if (p_arry[i].ProcessName == "AutoUpdateApp")//发现有名为QQ的进程
            //    {
            //        p_arry[i].Kill();//就结束它。
            //        return;
            //    }
            //}
           
            KillProcessByName("AutoUpdateApp");
            System.GC.Collect();//垃圾回收
        }
 
        /// <summary>
        /// 关闭进程
        /// </summary>
        /// <param name="processName">进程名</param>
        public void KillProcessByName(string processName)
        {
            try
            {
                Process[] myproc = Process.GetProcesses();
                foreach (Process item in myproc)
                {
                    if (item.ProcessName == processName)
                    {
                        item.CloseMainWindow();
                        item.Kill();
                    }
                }
            }
            catch { return; }
        }
 
    }
}

 

  

 

posted on   sunwugang  阅读(150)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
点击右上角即可分享
微信分享提示