用winform实现一个B/S代码更新打包工具

时间:2022-10-07 18:37:23

一个.net程序员必须拥有的能力就是可以随时随地写出一个自己需要的小工具,于是记录一下我的个人工具吧。

新建一个窗体应用项目,代码如下:

namespace 打包工具
{
    partial class 代码打包工具
    {
        /// <summary>
        /// 必需的设计器变量。
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// 清理所有正在使用的资源。
        /// </summary>
        /// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows 窗体设计器生成的代码

        /// <summary>
        /// 设计器支持所需的方法 - 不要修改
        /// 使用代码编辑器修改此方法的内容。
        /// </summary>
        private void InitializeComponent()
        {
            System.Windows.Forms.Label label2;
            System.Windows.Forms.Label label5;
            System.Windows.Forms.Label label6;
            this.panel2 = new System.Windows.Forms.Panel();
            this.Package_Btn = new System.Windows.Forms.Button();
            this.label1 = new System.Windows.Forms.Label();
            this.AsOfTheDate = new System.Windows.Forms.DateTimePicker();
            this.panel3 = new System.Windows.Forms.Panel();
            this.Show_Box = new System.Windows.Forms.RichTextBox();
            this.OpenFileUrl = new System.Windows.Forms.TextBox();
            this.OpenFile_Btn = new System.Windows.Forms.Button();
            this.OpenPackageFileUrl = new System.Windows.Forms.TextBox();
            this.PackageOpen_Btn = new System.Windows.Forms.Button();
            this.IgnoreDic = new System.Windows.Forms.TextBox();
            this.label3 = new System.Windows.Forms.Label();
            this.label4 = new System.Windows.Forms.Label();
            this.IgnoreFormate = new System.Windows.Forms.TextBox();
            this.Refresh_btn = new System.Windows.Forms.Button();
            this.panel1 = new System.Windows.Forms.Panel();
            label2 = new System.Windows.Forms.Label();
            label5 = new System.Windows.Forms.Label();
            label6 = new System.Windows.Forms.Label();
            this.panel2.SuspendLayout();
            this.panel3.SuspendLayout();
            this.panel1.SuspendLayout();
            this.SuspendLayout();
            // 
            // label2
            // 
            label2.AutoSize = true;
            label2.Location = new System.Drawing.Point(34, 94);
            label2.Name = "label2";
            label2.Size = new System.Drawing.Size(77, 12);
            label2.TabIndex = 7;
            label2.Text = "忽略文件夹:";
            // 
            // label5
            // 
            label5.AutoSize = true;
            label5.Location = new System.Drawing.Point(34, 121);
            label5.Name = "label5";
            label5.Size = new System.Drawing.Size(89, 12);
            label5.TabIndex = 16;
            label5.Text = "忽略文件格式:";
            // 
            // label6
            // 
            label6.AutoSize = true;
            label6.Font = new System.Drawing.Font("新宋体", 7.5F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
            label6.Location = new System.Drawing.Point(129, 76);
            label6.Name = "label6";
            label6.Size = new System.Drawing.Size(195, 10);
            label6.TabIndex = 19;
            label6.Text = "忽略文件夹和格式请用,(英文逗号)隔开";
            // 
            // panel2
            // 
            this.panel2.Controls.Add(this.Package_Btn);
            this.panel2.Controls.Add(this.label1);
            this.panel2.Controls.Add(this.AsOfTheDate);
            this.panel2.Location = new System.Drawing.Point(12, 320);
            this.panel2.Name = "panel2";
            this.panel2.Size = new System.Drawing.Size(776, 92);
            this.panel2.TabIndex = 1;
            // 
            // Package_Btn
            // 
            this.Package_Btn.BackColor = System.Drawing.Color.Red;
            this.Package_Btn.Cursor = System.Windows.Forms.Cursors.Hand;
            this.Package_Btn.Enabled = false;
            this.Package_Btn.Font = new System.Drawing.Font("宋体", 14.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
            this.Package_Btn.ForeColor = System.Drawing.SystemColors.Control;
            this.Package_Btn.Location = new System.Drawing.Point(36, 47);
            this.Package_Btn.Name = "Package_Btn";
            this.Package_Btn.Size = new System.Drawing.Size(711, 41);
            this.Package_Btn.TabIndex = 12;
            this.Package_Btn.Text = "打包";
            this.Package_Btn.UseVisualStyleBackColor = false;
            this.Package_Btn.Click += new System.EventHandler(this.Package_Btn_Click);
            // 
            // label1
            // 
            this.label1.AutoSize = true;
            this.label1.Location = new System.Drawing.Point(34, 17);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(65, 12);
            this.label1.TabIndex = 4;
            this.label1.Text = "打包时间:";
            // 
            // AsOfTheDate
            // 
            this.AsOfTheDate.CustomFormat = "yyyy-MM-dd HH:mm:ss";
            this.AsOfTheDate.Format = System.Windows.Forms.DateTimePickerFormat.Custom;
            this.AsOfTheDate.Location = new System.Drawing.Point(129, 11);
            this.AsOfTheDate.Name = "AsOfTheDate";
            this.AsOfTheDate.Size = new System.Drawing.Size(200, 21);
            this.AsOfTheDate.TabIndex = 0;
            // 
            // panel3
            // 
            this.panel3.Controls.Add(this.Show_Box);
            this.panel3.Location = new System.Drawing.Point(12, 12);
            this.panel3.Name = "panel3";
            this.panel3.Size = new System.Drawing.Size(776, 157);
            this.panel3.TabIndex = 2;
            // 
            // Show_Box
            // 
            this.Show_Box.Dock = System.Windows.Forms.DockStyle.Fill;
            this.Show_Box.Location = new System.Drawing.Point(0, 0);
            this.Show_Box.Name = "Show_Box";
            this.Show_Box.Size = new System.Drawing.Size(776, 157);
            this.Show_Box.TabIndex = 0;
            this.Show_Box.Text = "";
            // 
            // OpenFileUrl
            // 
            this.OpenFileUrl.Location = new System.Drawing.Point(131, 19);
            this.OpenFileUrl.Name = "OpenFileUrl";
            this.OpenFileUrl.ReadOnly = true;
            this.OpenFileUrl.Size = new System.Drawing.Size(524, 21);
            this.OpenFileUrl.TabIndex = 2;
            // 
            // OpenFile_Btn
            // 
            this.OpenFile_Btn.Location = new System.Drawing.Point(661, 19);
            this.OpenFile_Btn.Name = "OpenFile_Btn";
            this.OpenFile_Btn.Size = new System.Drawing.Size(28, 23);
            this.OpenFile_Btn.TabIndex = 3;
            this.OpenFile_Btn.Text = "";
            this.OpenFile_Btn.UseVisualStyleBackColor = true;
            this.OpenFile_Btn.Click += new System.EventHandler(this.OpenFile_Btn_Click);
            // 
            // OpenPackageFileUrl
            // 
            this.OpenPackageFileUrl.Location = new System.Drawing.Point(131, 46);
            this.OpenPackageFileUrl.Name = "OpenPackageFileUrl";
            this.OpenPackageFileUrl.ReadOnly = true;
            this.OpenPackageFileUrl.Size = new System.Drawing.Size(524, 21);
            this.OpenPackageFileUrl.TabIndex = 5;
            // 
            // PackageOpen_Btn
            // 
            this.PackageOpen_Btn.Location = new System.Drawing.Point(661, 47);
            this.PackageOpen_Btn.Name = "PackageOpen_Btn";
            this.PackageOpen_Btn.Size = new System.Drawing.Size(28, 23);
            this.PackageOpen_Btn.TabIndex = 6;
            this.PackageOpen_Btn.Text = "";
            this.PackageOpen_Btn.UseVisualStyleBackColor = true;
            this.PackageOpen_Btn.Click += new System.EventHandler(this.PackageOpen_Btn_Click);
            // 
            // IgnoreDic
            // 
            this.IgnoreDic.Location = new System.Drawing.Point(129, 91);
            this.IgnoreDic.Name = "IgnoreDic";
            this.IgnoreDic.Size = new System.Drawing.Size(524, 21);
            this.IgnoreDic.TabIndex = 13;
            // 
            // label3
            // 
            this.label3.AutoSize = true;
            this.label3.Location = new System.Drawing.Point(34, 24);
            this.label3.Name = "label3";
            this.label3.Size = new System.Drawing.Size(77, 12);
            this.label3.TabIndex = 14;
            this.label3.Text = "打包文件夹:";
            // 
            // label4
            // 
            this.label4.AutoSize = true;
            this.label4.Location = new System.Drawing.Point(34, 52);
            this.label4.Name = "label4";
            this.label4.Size = new System.Drawing.Size(77, 12);
            this.label4.TabIndex = 15;
            this.label4.Text = "结果文件夹:";
            // 
            // IgnoreFormate
            // 
            this.IgnoreFormate.Location = new System.Drawing.Point(129, 118);
            this.IgnoreFormate.Name = "IgnoreFormate";
            this.IgnoreFormate.Size = new System.Drawing.Size(524, 21);
            this.IgnoreFormate.TabIndex = 17;
            // 
            // Refresh_btn
            // 
            this.Refresh_btn.Location = new System.Drawing.Point(661, 116);
            this.Refresh_btn.Name = "Refresh_btn";
            this.Refresh_btn.Size = new System.Drawing.Size(75, 23);
            this.Refresh_btn.TabIndex = 18;
            this.Refresh_btn.Text = "更新配置";
            this.Refresh_btn.UseVisualStyleBackColor = true;
            this.Refresh_btn.Click += new System.EventHandler(this.Refresh_btn_Click);
            // 
            // panel1
            // 
            this.panel1.Controls.Add(label6);
            this.panel1.Controls.Add(this.Refresh_btn);
            this.panel1.Controls.Add(this.IgnoreFormate);
            this.panel1.Controls.Add(this.OpenFileUrl);
            this.panel1.Controls.Add(label5);
            this.panel1.Controls.Add(this.OpenFile_Btn);
            this.panel1.Controls.Add(this.label4);
            this.panel1.Controls.Add(this.OpenPackageFileUrl);
            this.panel1.Controls.Add(this.label3);
            this.panel1.Controls.Add(this.PackageOpen_Btn);
            this.panel1.Controls.Add(this.IgnoreDic);
            this.panel1.Controls.Add(label2);
            this.panel1.Location = new System.Drawing.Point(12, 175);
            this.panel1.Name = "panel1";
            this.panel1.Size = new System.Drawing.Size(776, 141);
            this.panel1.TabIndex = 3;
            // 
            // 代码打包工具
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(800, 436);
            this.Controls.Add(this.panel1);
            this.Controls.Add(this.panel3);
            this.Controls.Add(this.panel2);
            this.Name = "代码打包工具";
            this.Text = "代码打包工具 By 余承浩";
            this.panel2.ResumeLayout(false);
            this.panel2.PerformLayout();
            this.panel3.ResumeLayout(false);
            this.panel1.ResumeLayout(false);
            this.panel1.PerformLayout();
            this.ResumeLayout(false);

        }

        #endregion

        private System.Windows.Forms.Panel panel2;
        private System.Windows.Forms.Button Package_Btn;
        private System.Windows.Forms.DateTimePicker AsOfTheDate;
        private System.Windows.Forms.Panel panel3;
        private System.Windows.Forms.RichTextBox Show_Box;
        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.TextBox OpenFileUrl;
        private System.Windows.Forms.Button OpenFile_Btn;
        private System.Windows.Forms.TextBox OpenPackageFileUrl;
        private System.Windows.Forms.Button PackageOpen_Btn;
        private System.Windows.Forms.TextBox IgnoreDic;
        private System.Windows.Forms.Label label3;
        private System.Windows.Forms.Label label4;
        private System.Windows.Forms.TextBox IgnoreFormate;
        private System.Windows.Forms.Button Refresh_btn;
        private System.Windows.Forms.Panel panel1;
    }
}

逻辑代码如下:

  1 using System;
  2 using System.Collections.Generic;
  3 using System.IO;
  4 using System.Linq;
  5 using System.Windows.Forms;
  6 using 打包工具.Util;
  7 
  8 namespace 打包工具
  9 {
 10     public partial class 代码打包工具 : Form
 11     {
 12         /// <summary>
 13         /// 打包文件存储位置
 14         /// </summary>
 15         private static string OpenPackageFolder = string.Empty;
 16         /// <summary>
 17         /// 需打包文件位置
 18         /// </summary>
 19         private static string PackageFolder = string.Empty;
 20         /// <summary>
 21         /// 不参与打包的文件格式
 22         /// </summary>
 23         private static string noPackageFormatListStr = string.Empty;
 24         /// <summary>
 25         /// 不参与打包的文件夹
 26         /// </summary>
 27         private static string noPackageDicListStr = string.Empty;
 28         /// <summary>
 29         /// 不参与打包的文件格式列表
 30         /// </summary>
 31         private static List<string> noPackageFormatList = new List<string>();
 32         /// <summary>
 33         /// 不参与打包的文件夹列表
 34         /// </summary>
 35         private static List<string> noPackageDicList = new List<string>();
 36         public 代码打包工具()
 37         {
 38             InitializeComponent();
 39             GetAllConfig();
 40             this.OpenFileUrl.Text = PackageFolder;
 41             this.OpenPackageFileUrl.Text = OpenPackageFolder;
 42             this.IgnoreDic.Text = noPackageDicListStr;
 43             this.IgnoreFormate.Text = noPackageFormatListStr;
 44             if (!string.IsNullOrEmpty(OpenPackageFolder))
 45             {
 46                 Package_Btn.Enabled = true;
 47                 Package_Btn.BackColor = System.Drawing.Color.Green;
 48             }
 49         }
 50         private void GetAllConfig() {
 51             var configJson = Config.GetConfig();
 52             OpenPackageFolder = configJson.OpenPackageFolder;
 53             PackageFolder = configJson.PackageFolder;
 54             noPackageFormatListStr = configJson.noPackageFormatList;
 55             noPackageDicListStr = configJson.noPackageDicList;
 56             noPackageFormatList = noPackageFormatListStr.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList();
 57             noPackageDicList = noPackageDicListStr.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList();
 58     }
 59         /// <summary>
 60         /// 选择需要打包的文件夹
 61         /// </summary>
 62         /// <param name="sender"></param>
 63         /// <param name="e"></param>
 64         private void OpenFile_Btn_Click(object sender, EventArgs e)
 65         {
 66             FolderBrowserDialog dialog = new FolderBrowserDialog();
 67             dialog.ShowNewFolderButton = true;
 68             if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
 69             {
 70                 this.OpenFileUrl.Text = dialog.SelectedPath;
 71                 PackageFolder = dialog.SelectedPath;
 72                 ShowTime_Box("成功获取打包文件夹。");
 73                 if (!string.IsNullOrEmpty(OpenPackageFolder))
 74                 {
 75                     Package_Btn.Enabled = true;
 76                     Package_Btn.BackColor = System.Drawing.Color.Green;
 77                 }
 78 
 79             }
 80         }
 81         /// <summary>
 82         /// 
 83         /// </summary>
 84         /// <param name="sender"></param>
 85         /// <param name="e"></param>
 86         private void PackageOpen_Btn_Click(object sender, EventArgs e)
 87         {
 88             FolderBrowserDialog dialog = new FolderBrowserDialog();
 89             dialog.ShowNewFolderButton = true;
 90             if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
 91             {
 92                 this.OpenPackageFileUrl.Text = dialog.SelectedPath;
 93                 OpenPackageFolder = dialog.SelectedPath;
 94                 ShowTime_Box("成功获取打包后保存文件夹。");
 95                 if (!string.IsNullOrEmpty(PackageFolder))
 96                 {
 97                     Package_Btn.Enabled = true;
 98                     Package_Btn.BackColor = System.Drawing.Color.Green;
 99                 }
100             }
101         }
102         private void Package_Btn_Click(object sender, EventArgs e)
103         {
104             var date = AsOfTheDate.Value;
105             ShowTime_Box("正在打包,请稍后……");
106             CopyDirectory(PackageFolder,OpenPackageFolder, date);
107             ShowTime_Box("打包完成。");
108         }
109 
110         public void ShowTime_Box(string msg)
111         {
112             Invoke(new Action(delegate {
113                 Show_Box.AppendText(DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss") + "\r\n" + msg + "\r\n");
114                 Show_Box.Focus();//获取焦点
115                 Show_Box.Select(Show_Box.TextLength, 0);//光标定位到文本最后
116                 Show_Box.ScrollToCaret();//滚动到光标处
117             }));
118         }
119         /// <summary>
120         /// 打包文件方法
121         /// </summary>
122         /// <param name="srcPath">打包路径</param>
123         /// <param name="destPath">更新包路径</param>
124         /// <param name="date">筛选时间</param>
125         public static void CopyDirectory(string srcPath, string destPath,DateTime date)
126         {
127             try
128             {
129                 var dir = new DirectoryInfo(srcPath);
130                 var fileinfo = dir.GetFileSystemInfos();  //获取目录下(不包含子目录)的文件和子目录
131                 foreach (FileSystemInfo i in fileinfo)
132                 {
133                     if (i is DirectoryInfo)     //判断是否文件夹
134                     {
135                         if (!noPackageDicList.Contains(i.Name))
136                         {
137                             var iDir = i as DirectoryInfo;
138                             long len = 0;
139                             foreach (var ilen in iDir.GetDirectories())
140                             {
141                                 CopyDirectory(ilen.FullName, ilen.FullName.Replace(srcPath, destPath), date);    //递归调用复制子文件夹
142                             }
143                             foreach (var ilen in iDir.GetFiles())
144                             {
145                                 if (!noPackageFormatList.Contains(ilen.Extension.ToLower()) && date <= ilen.LastWriteTime)
146                                     len += ilen.Length;
147                             }
148                             if (len > 0)
149                             {
150                                 if (!Directory.Exists(destPath + "\\" + i.Name))
151                                 {
152                                     Directory.CreateDirectory(destPath + "\\" + i.Name);   //目标目录下不存在此文件夹即创建子文件夹
153                                 }
154                                 CopyDirectory(i.FullName, destPath + "\\" + i.Name, date);    //递归调用复制子文件夹
155                             }
156                         }
157 
158                     }
159                     else
160                     {
161                         if (!noPackageFormatList.Contains(i.Extension.ToLower()) && date <= i.LastWriteTime)
162                         {
163                             if (!Directory.Exists(destPath))
164                             {
165                                 Directory.CreateDirectory(destPath);   //目标目录下不存在此文件夹即创建子文件夹
166                             }
167                             File.Copy(i.FullName, destPath + "\\" + i.Name, true);      //不是文件夹即复制文件,true表示可以覆盖同名文件
168                         }
169                     }
170                 }
171             }
172             catch (Exception e)
173             {
174                 throw;
175             }
176         }
177         private void Refresh_btn_Click(object sender, EventArgs e)
178         {
179             Config.ModifeConfig(new ConfigJson {
180                 OpenPackageFolder= this.OpenPackageFileUrl.Text,
181                 PackageFolder = this.OpenFileUrl.Text,
182                 noPackageFormatList = this.IgnoreFormate.Text,
183                 noPackageDicList = this.IgnoreDic.Text,
184             });
185             GetAllConfig();
186             ShowTime_Box("更新成功。");
187         }
188     }
189 }

 

一些相关的Util.Config工具类代码如下:

 1 using System;
 2 using System.Collections.Generic;
 3 using System.IO;
 4 using System.Linq;
 5 using System.Text;
 6 using System.Threading.Tasks;
 7 using Newtonsoft.Json;
 8 
 9 namespace 打包工具.Util
10 {
11     public class Config
12     {
13         private static string urlConfig = "../../Config.json";
14         /// <summary>
15         /// 根据Key修改Value
16         /// </summary>
17         /// <param name="key">要修改的Key</param>
18         /// <param name="value">要修改为的值</param>
19         public static void SetValue(string key, string value)
20         {
21             System.Xml.XmlDocument xDoc = new System.Xml.XmlDocument();
22             xDoc.Load("../../App.config");
23             System.Xml.XmlNode xNode;
24             System.Xml.XmlElement xElem1;
25             System.Xml.XmlElement xElem2;
26             xNode = xDoc.SelectSingleNode("//appSettings");
27             xElem1 = (System.Xml.XmlElement)xNode.SelectSingleNode("//add[@key='" + key + "']");
28             if (xElem1 != null) xElem1.SetAttribute("value", value);
29             else
30             {
31                 xElem2 = xDoc.CreateElement("add");
32                 xElem2.SetAttribute("key", key);
33                 xElem2.SetAttribute("value", value);
34                 xNode.AppendChild(xElem2);
35             }
36             xDoc.Save("../../App.config");
37         }
38         /// <summary>
39         /// 获取配置信息
40         /// </summary>
41         /// <returns></returns>
42         public static ConfigJson GetConfig() {
43             StreamReader file = File.OpenText(urlConfig);
44             var Json = file.ReadToEnd();
45             file.Dispose();
46             return Json == null ? null : JsonConvert.DeserializeObject<ConfigJson>(Json);
47         }
48         /// <summary>
49         /// 修改配置信息
50         /// </summary>
51         /// <returns></returns>
52         public static void ModifeConfig(ConfigJson configJson)
53         {
54             var configJsonStr = JsonConvert.SerializeObject(configJson);
55             FileStream fs = new FileStream(urlConfig, FileMode.OpenOrCreate);
56             StreamReader sr = new StreamReader(fs, Encoding.GetEncoding("GB2312"));
57             StreamWriter sw = new StreamWriter(fs, Encoding.UTF8);
58             sw.Write(configJsonStr);  //这里是写入的内容
59             sw.Flush();
60             sw.Close();
61             sr.Close();
62         }
63     }
64     public class ConfigJson
65     {
66         /// <summary>
67         /// 打包文件存储位置
68         /// </summary>
69         public string OpenPackageFolder { set; get; }
70         /// <summary>
71         /// 需打包文件位置
72         /// </summary>
73         public string PackageFolder { set; get; }
74         /// <summary>
75         /// 不参与打包的文件格式
76         /// </summary>
77         public string noPackageFormatList { set; get; }
78         /// <summary>
79         /// 不参与打包的文件夹
80         /// </summary>
81         public string noPackageDicList { set; get; }
82     }
83 }

 

其中相关的配置项使用的是json文件,格式如下:

{
  "OpenPackageFolder": "C",
  "PackageFolder": "D",
  "noPackageFormatList": ".config,.csproj,.cs,.pdb,.user,.sln",
  "noPackageDicList": ".svn,.nuget,.vs,obj"
}

最开始的版本思路是筛选所有的符合条件的文件夹并复制到目标文件夹内,等所有的复制工作完成之后,再遍历目标文件夹并删除空的文件夹。后来想了一下,可能会误删文件,导致一些不好的后果;于是改变思路,每次复制文件夹之前先判断该文件夹符合条件的文件大小是否为0,为0则不复制该文件夹,这样就避免了删除的操作。