安装包,创建快捷方式,开机启动项,配置文件参数覆盖窗体类库

//using IWshRuntimeLibrary;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml;

namespace setup
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();        
            label1.Text = "";
            textBox2.Visible = false;
        }
       static  string Parameter_path1_old = "";
      static  string Parameter_path2_old = "";
       static  string Parameter_path3_old = "";
       static  string Parameter_path4_old = "";
       static string Parameter_path1_new = "";
       static string Parameter_path2_new = "";
       static string Parameter_path3_new = "";
       static string Parameter_path4_new = "";

        private void button_Install_Click(object sender, EventArgs e)
        {
           
            button_Install.Enabled = false;
            textBox2.Visible = true;
            label1.Text = "请等待...";
            string installPath = GetInstallPath();
            if(!Directory.Exists(installPath))
            {
                Directory.CreateDirectory(installPath);
            }
            string path1 =installPath+"//Debug1" ;
            string path2 = installPath + "//Debug2";
            textBox2.Text = installPath;
            textBox2.Enabled = false;

            string sourcePath = AppDomain.CurrentDomain.BaseDirectory+"Debug";
            if (!Directory.Exists(sourcePath) )
            {
                return;
            }
            Task.Factory.StartNew(() => {
                if (!Directory.Exists(path1))
                {
                    Directory.CreateDirectory(path1);
                    CopyDirectory(sourcePath, path1);
                    ShortcutCreator.SetSetupWindowOpenRun(path1 + "//Unfix.exe", "Unfix", "拉曼光谱仪");
                    ShortcutCreator.CreateShortcutOnDesktop("Unfix", path1 + "//Unfix.exe"); 
                    this.Invoke(new Action(() => { label1.Text = "安装完成"; })); 
                    return;//首次安装
                }

                if (Directory.Exists(path2))
                {
                    DelectDir(path2);
                }
                Directory.CreateDirectory(path2);
                CopyDirectory(path1, path2);
                DelectDir(path1);
                Directory.CreateDirectory(path1);
                CopyDirectory(sourcePath, path1);

                Parameter_path1_old = path2 + "//SaveParameters-Small.xml";
                Parameter_path2_old = path2 + "//SaveParameters-Middle-NemoN532.xml";
                Parameter_path3_old = path2 + "//SaveParameters-Middle-NemoN532Or785.xml";
                Parameter_path4_old = path2 + "//Unfix.exe.config";

                Parameter_path1_new = path1 + "//SaveParameters-Small.xml";
                Parameter_path2_new = path1 + "//SaveParameters-Middle-NemoN532.xml";
                Parameter_path3_new = path1 + "//SaveParameters-Middle-NemoN532Or785.xml";
                Parameter_path4_new = path1 + "//Unfix.exe.config";
                UpDataConfig(Parameter_path1_new, Parameter_path1_old);
                UpDataConfig(Parameter_path2_new, Parameter_path2_old);
                UpDataConfig(Parameter_path3_new, Parameter_path3_old);
                UpdataAppConfig(Parameter_path4_new, Parameter_path4_old);//更新应用程序配置
                ShortcutCreator.SetSetupWindowOpenRun(path1 + "//Unfix.exe", "Unfix", "拉曼光谱仪");
                ShortcutCreator.CreateShortcutOnDesktop("Unfix", path1 + "//Unfix.exe"); 
                this.Invoke(new Action(() => { label1.Text = "安装完成"; })); 
            
            
            });
           
        }
        public static void CopyDirectory(string srcPath, string destPath)
        {
          
                try
                {

                    DirectoryInfo dir = new DirectoryInfo(srcPath);
                    FileSystemInfo[] fileinfo = dir.GetFileSystemInfos();  //获取目录下(不包含子目录)的文件和子目录
                    foreach (FileSystemInfo i in fileinfo)
                    {
                        if (i is DirectoryInfo)     //判断是否文件夹
                        {
                            if (!Directory.Exists(destPath + "\\" + i.Name))
                            {
                                Directory.CreateDirectory(destPath + "\\" + i.Name);   //目标目录下不存在此文件夹即创建子文件夹
                            }
                            CopyDirectory(i.FullName, destPath + "\\" + i.Name);    //递归调用复制子文件夹
                        }
                        else
                        {
                            //File.Create(destPath + "\\" + i.Name);
                            File.Copy(i.FullName, destPath + "\\" + i.Name, true);      //不是文件夹即复制文件,true表示可以覆盖同名文件
                        }
                    }
                }
                catch (Exception e)
                {
                    MessageBox.Show(e.ToString());
                }
                            
         
        }

       
        public static void UpDataConfig(string pathNew,string pathOld)//参数配置更新
        {
            oldXd = null;//初始化加载赋值
            XmlDocument xmlDocument = new XmlDocument();
            xmlDocument.Load(pathNew);
            XmlNodeList xmlNLis = xmlDocument.ChildNodes;
            foreach(XmlNode xn in xmlNLis[1])
            {
               foreach(XmlNode xn2 in xn.ChildNodes)
               {
                   string value=GetParameterValue(pathOld,xn.Name, xn2.Name, "");
                  if( value!=null)//获取参数值
                  {
                      xn2.InnerText = value;
                  }
                  
                 

               }

扫描二维码关注公众号,回复: 4649230 查看本文章

            }
            xmlDocument.Save(pathNew);

        }
        public void UpdataAppConfig(string pathNew, string pathOld)//更新应用程序配置
        {
            oldXd = null;//初始化加载赋值
            XmlDocument xmlDocument = new XmlDocument();
            xmlDocument.Load(pathNew);
            XmlNodeList xmlNLis = xmlDocument.ChildNodes;
        
            foreach (XmlNode xn in xmlNLis[1].ChildNodes)
            {
                if (xn.Name == "#comment" || xn.Name == "configSections")
                {
                    continue;
                }
                foreach (XmlNode xn2 in xn.ChildNodes)
                {
                  foreach(XmlNode xn3 in xn2.ChildNodes)
                  {
                      if (xn3.Name == "#comment") continue;
                      string value = APPConfigHelper.GetValue(pathOld, xn3.Attributes[0].Value, "");
                      if (value != null&&value!="")//获取参数值
                      {
                          xn3.Attributes[1].Value = value;
                      }

                  }
                   

                }

            }
            xmlDocument.Save(pathNew);

        }


        static XmlDocument oldXd;//老配置文件
        public static string GetParameterValue(string filePath,string parameterType, string parameterName, string defaultValue)//获取参数值
        {


          if(oldXd==null)
          {
              oldXd = new XmlDocument();
              oldXd.Load(filePath);
          }
          
            XmlNode pXmlNode = oldXd.ChildNodes[1];
            XmlNodeList xmlNodeList = pXmlNode.ChildNodes;
            foreach (XmlNode xmlNode in xmlNodeList)
            {
                if (xmlNode.Name == parameterType)
                {
                    XmlNodeList xmLis = xmlNode.ChildNodes;
                    foreach (XmlNode xx in xmLis)
                    {
                        if (xx.Name == parameterName)
                        {

                            return xx.InnerText;

                        }


                    }

                }

            }
            return defaultValue;

        }


        public  string GetInstallPath()//获取路径
        {
            string configPath = AppDomain.CurrentDomain.BaseDirectory+ "setup.exe.config";

           string installPath= GetValue(configPath, "InstallPath", "");//获取配置文件值

            return installPath;
        }
        public static string GetValue(string configPath,string key, string value)//获取配置文件值
        {

            XmlDocument doc = new XmlDocument();
            {
                string strFileName = configPath;
                doc.Load(strFileName);//获得配置文件的全路径
                XmlNodeList nodes = doc.GetElementsByTagName("add");//找出名称为“add”的所有元素
                for (int i = 0; i < nodes.Count; i++)
                {
                    //获得将当前元素的key属性
                    XmlAttribute att = nodes[i].Attributes["key"];
                    //根据元素的第一个属性来判断当前的元素是不是目标元素
                    if (att.Value == key)
                    {
                        //对目标元素中的第二个属性赋值

                        att = nodes[i].Attributes["value"];
                        return att.Value;


                    }
                }
                //保存上面的修改

                //doc.Save(strFileName);

                return value;
            }

        }
        public static void DelectDir(string srcPath)//删除文件夹及所有文件
        {
            try
            {
                DirectoryInfo dir = new DirectoryInfo(srcPath);
                FileSystemInfo[] fileinfo = dir.GetFileSystemInfos();  //返回目录中所有文件和子目录
                foreach (FileSystemInfo i in fileinfo)
                {
                    if (i is DirectoryInfo)            //判断是否文件夹
                    {
                        DirectoryInfo subdir = new DirectoryInfo(i.FullName);
                        subdir.Delete(true);          //删除子目录和文件
                    }
                    else
                    {
                        File.Delete(i.FullName);      //删除指定文件
                    }
                }
                Directory.Delete(srcPath);
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString());
            }
        }

    }


    public class APPConfigHelper
    {
        public static object obj = 500;
       


        public static string GetValue(string filePath, string key, string value)//获取配置文件值
        {
            lock (obj)
            {
                XmlDocument doc = new XmlDocument();
                {
                    string strFileName = filePath;
                    doc.Load(strFileName);//获得配置文件的全路径
                    XmlNodeList nodes = doc.GetElementsByTagName("add");//找出名称为“add”的所有元素
                    for (int i = 0; i < nodes.Count; i++)
                    {
                        //获得将当前元素的key属性
                        XmlAttribute att = nodes[i].Attributes["key"];
                        //根据元素的第一个属性来判断当前的元素是不是目标元素
                        if (att.Value == key)
                        {
                            //对目标元素中的第二个属性赋值

                            att = nodes[i].Attributes["value"];
                            return att.Value;


                        }
                    }
                    //保存上面的修改

                    //doc.Save(strFileName);

                    return value;
                }
            }
        }

        public static void SetValue(string filePath, string key, string value)//获取配置文件值
        {
            lock (obj)
            {
                XmlDocument doc = new XmlDocument();
                {
                    string strFileName = filePath;
                    doc.Load(strFileName);//获得配置文件的全路径
                    XmlNodeList nodes = doc.GetElementsByTagName("add");//找出名称为“add”的所有元素
                    for (int i = 0; i < nodes.Count; i++)
                    {
                        //获得将当前元素的key属性
                        XmlAttribute att = nodes[i].Attributes["key"];
                        //根据元素的第一个属性来判断当前的元素是不是目标元素
                        if (att.Value == key)
                        {
                            //对目标元素中的第二个属性赋值

                            att = nodes[i].Attributes["value"];
                            att.Value = value;

                            break;
                        }
                    }
                    //保存上面的修改

                    doc.Save(strFileName);

                }
            }
        }


    }

   
   
    public class ShortcutCreator
     {

         /// <summary>
         /// 创建快捷方式的函数
         /// </summary>
         /// <remarks></remarks>
         /// <summary> 
         /// 将文件放到启动文件夹中开机启动 
         /// </summary> 
         /// <param name="setupPath">启动程序</param> 
         /// <param name="linkname">快捷方式名称</param> 
         /// <param name="description">描述</param> 
         public static void SetSetupWindowOpenRun(string setupPath, string linkname, string description)
         {
             string desktop = Environment.GetFolderPath(Environment.SpecialFolder.Startup) + "\\" + linkname + ".lnk";
             if (System.IO.File.Exists(desktop)) System.IO.File.Delete(desktop);
             IWshRuntimeLibrary.WshShell shell; IWshRuntimeLibrary.IWshShortcut shortcut;
             try
             {
                 shell = new IWshRuntimeLibrary.WshShell();
                 shortcut = (IWshRuntimeLibrary.IWshShortcut)shell.CreateShortcut(desktop);
                 shortcut.TargetPath = setupPath;//程序路径   
                 shortcut.Arguments = "";//参数   
                 shortcut.Description = description;//描述   
                 shortcut.WorkingDirectory = System.IO.Path.GetDirectoryName(setupPath);//程序所在目录   
                 shortcut.IconLocation = setupPath;//图标      
                 shortcut.WindowStyle = 1; shortcut.Save();
             }
             catch (Exception ex)
             {
                 System.Windows.Forms.MessageBox.Show(ex.Message, "友情提示");
             }
             finally
             {
                 shell = null; shortcut = null;
             }
         } 


         //需要引入IWshRuntimeLibrary,搜索Windows Script Host Object Model

        /// <summary>
         /// 创建快捷方式
         /// </summary>
         /// <param name="directory">快捷方式所处的文件夹</param>
         /// <param name="shortcutName">快捷方式名称</param>         /// <param name="targetPath">目标路径</param>         /// <param name="description">描述</param>
        /// <param name="iconLocation">图标路径,格式为"可执行文件或DLL路径, 图标编号",
        /// 例如System.Environment.SystemDirectory + "\\" + "shell32.dll, 165"</param>
         /// <remarks></remarks>
         public static void CreateShortcut(string directory, string shortcutName, string targetPath,
             string description = null, string iconLocation = null)
         {
             if (!System.IO.Directory.Exists(directory))
            {
                 System.IO.Directory.CreateDirectory(directory);
             }
 
            string shortcutPath = Path.Combine(directory, string.Format("{0}.lnk", shortcutName));
            IWshRuntimeLibrary.WshShell shell = new IWshRuntimeLibrary.WshShell();
            IWshRuntimeLibrary.IWshShortcut shortcut = (IWshRuntimeLibrary.IWshShortcut)shell.CreateShortcut(shortcutPath);//创建快捷方式对象
             shortcut.TargetPath = targetPath;//指定目标路径
             shortcut.WorkingDirectory = Path.GetDirectoryName(targetPath);//设置起始位置
             shortcut.WindowStyle = 1;//设置运行方式,默认为常规窗口
            shortcut.Description = description;//设置备注
             shortcut.IconLocation = string.IsNullOrWhiteSpace(iconLocation) ? targetPath : iconLocation;//设置图标路径
             shortcut.Save();//保存快捷方式
        }
 
         /// <summary>
        /// 创建桌面快捷方式
        /// </summary>
         /// <param name="shortcutName">快捷方式名称</param>
         /// <param name="targetPath">目标路径</param>
         /// <param name="description">描述</param>
        /// <param name="iconLocation">图标路径,格式为"可执行文件或DLL路径, 图标编号"</param>
         /// <remarks></remarks>
         public static void CreateShortcutOnDesktop(string shortcutName, string targetPath, 
             string description = null, string iconLocation = null)
         {
             string desktop = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);//获取桌面文件夹路径
             CreateShortcut(desktop, shortcutName, targetPath, description, iconLocation);
         }

    }
 
}
 

猜你喜欢

转载自blog.csdn.net/u011555996/article/details/84937026