c#制作类似qq安装程序一样的单文件程序安装包

 更新时间:2014年01月11日 10:44:13   作者:  
c#制作单文件安装程序,可安装windows服务,类似安装QQ,大家参考使用吧

复制代码 代码如下:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Xml;
using System.IO;
using System.IO.Compression;
using System.Resources;
using System.Net;
using System.Web.Services.Description;
using System.Diagnostics;
using System.Runtime.InteropServices;

namespace MON.Client
{
    public partial class MainForm : Form
    {
        bool testFlag = false;
        Dictionary<string, string> dic;
        Thread t;
        public MainForm()
        {

            InitializeComponent();
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            dic = new Dictionary<string, string>();
            groupBox1.Visible = true;
            groupBox2.Visible = false;
        }

        /// <summary>
        /// 安装路径
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void InstallPathBTN_Click(object sender, EventArgs e)
        {
            DialogResult dr = FolerBrowserCreator.ShowDialog();
            if (DialogResult.OK == dr)
            {
                InstallPathTB.Text = FolerBrowserCreator.SelectedPath;
                if (dic.ContainsKey("installPath"))
                {
                    dic["installPath"] = InstallPathTB.Text;                   
                }
                else
                {
                    dic.Add("installPath", InstallPathTB.Text);
                }
                if (string.IsNullOrEmpty(LogInstallPahtTB.Text))
                {
                    LogInstallPahtTB.Text = Path.Combine(InstallPathTB.Text, "log");
                    if (dic.ContainsKey("logPath"))
                    {
                        dic["logPath"] = LogInstallPahtTB.Text;                       
                    }
                    else
                    {
                        dic.Add("logPath", LogInstallPahtTB.Text);
                    }
                }
            }
        }
        /// <summary>
        /// 日志路径
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void LogPathBrowseBtn_Click(object sender, EventArgs e)
        {
            DialogResult dr = FolerBrowserCreator.ShowDialog();
            if (DialogResult.OK == dr)
            {
                LogInstallPahtTB.Text = FolerBrowserCreator.SelectedPath;
                if (dic.ContainsKey("logPath"))
                {
                    dic["logPath"] = LogInstallPahtTB.Text;                   
                }
                else
                {
                    dic.Add("logPath", LogInstallPahtTB.Text);
                }
            }
        }
        /// <summary>
        /// 测试webservice;
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void testWebServiceBTN_Click(object sender, EventArgs e)
        {
            testWebServiceBTN.Enabled = false;
            TestService();
            if (testFlag)
            {
                MessageBox.Show("测试通过", "系统提示", MessageBoxButtons.OK);
            }
            else
            {
                MessageBox.Show("网站地址有误", "系统提示", MessageBoxButtons.OK);
            }
            testWebServiceBTN.Enabled = true;
        }
        /// <summary>
        /// 测试webservice
        /// </summary>
        void TestService()
        {
            WebClient wc = new WebClient();
            Stream stream1 = null;
            Stream stream2 = null;
            try
            {
                var url = WebSiteTB.Text.Trim().ToUpper();
                if (!url.EndsWith("/MON/MONSERVICE.ASMX"))
                {
                    url = url.TrimEnd('/') + "/MON/MONSERVICE.ASMX";
                }
                if (dic.ContainsKey("webService"))
                {
                    dic["webService"] = url;
                }
                else
                {
                    dic.Add("webService", url);
                }
                stream1 = wc.OpenRead(url + "?op=GetMachineConfig");
                stream2 = wc.OpenRead(url + "?op=UpdateServerStatus");
                if (stream1.CanRead && stream2.CanRead)
                {
                    testFlag = true;
                }
            }
            catch
            {
                testFlag = false;
            }
            finally
            {
                wc.Dispose();
                if (stream1 != null)
                {
                    stream1.Close();
                }
                if (stream2 != null)
                {
                    stream2.Close();
                }

            }
        }
        /// <summary>
        /// 开始安装
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void StartBtn_Click(object sender, EventArgs e)
        {
            if (!Directory.Exists(InstallPathTB.Text.Trim()))
            {
                MessageBox.Show("安装路径有误", "系统提示", MessageBoxButtons.OK);
                return;
            }

            if (LogInstallPahtTB.Text.Trim().StartsWith(InstallPathTB.Text.Trim()))
            {
                if (!Directory.Exists(LogInstallPahtTB.Text.Trim()))
                {
                    Directory.CreateDirectory(LogInstallPahtTB.Text.Trim());
                }
            }
            else
            {
                if (!Directory.Exists(LogInstallPahtTB.Text.Trim()))
                {
                    MessageBox.Show("日志路径有误", "系统提示", MessageBoxButtons.OK);
                    return;
                }
            }
            if (testFlag == false)
            {
                TestService();//test过就不用再test一次了
            }
            if (testFlag == false)
            {
                MessageBox.Show("网站地址有误", "系统提示", MessageBoxButtons.OK);
                return;
            }
            try
            {
                int days = Convert.ToInt32(DaysTB.Text.Trim());
                if (days < 1)
                {
                    throw new Exception();
                }
            }
            catch
            {
                MessageBox.Show("日志保存天数有误", "系统提示", MessageBoxButtons.OK);
                return;
            }
            dic.Add("logDays", DaysTB.Text.Trim());
            groupBox1.Visible = false;
            groupBox2.Visible = true;
            InstallInfoTB.Text = "开始安装";
            t = new Thread(new ThreadStart(InstallJob));
            t.Start();
        }
        /// <summary>
        /// 安装线程
        /// </summary>
        void InstallJob()
        {
            WriteLine("准备安装环境...");
            var configPath = Path.Combine(dic["installPath"], "MON.WS.exe.config");
            var exePath = configPath.TrimEnd(".config".ToCharArray());
            var args = new List<string>();

            args.Add(@"net stop 服务器性能监控UTRY");
            args.Add(@"%SystemRoot%\Microsoft.NET\Framework\v2.0.50727\InstallUtil.exe /u " + exePath);
            args.Add("exit");
            if (!cmdCommand(args))
            {
                WriteLine("在卸载原有服务时出现异常");
                WriteLine("安装失败");
                return;
            }

            WriteLine("释放配置文件...");
            if (!releaseConfig(dic, configPath))
            {
                WriteLine("释放配置文件过程中出现异常");
                WriteLine("安装失败");
                return;
            }
            WriteLine("配置文件释放完毕...");

            WriteLine("释放可执行文件...");
            if (!releaseExe(exePath))
            {
                WriteLine("释放可执行文件时出现异常");
                WriteLine("安装失败");
                return;
            }
            WriteLine("可执行文件释放完毕...");

            WriteLine("开始安装服务...");
            args.Clear();
            args.Add(@"%SystemRoot%\Microsoft.NET\Framework\v2.0.50727\InstallUtil.exe " + exePath);
            args.Add(@"net start 服务器性能监控UTRY");
            args.Add("exit");
            if (!cmdCommand(args))
            {
                WriteLine("在安装和启动服务时出现异常");
                WriteLine("安装失败");
                return;
            }
            WriteLine("服务安装成功");
            WriteLine("安装成功");
        }
        /// <summary>
        /// 释放exe
        /// </summary>
        /// <param name="exePath"></param>
        bool releaseExe(string exePath)
        {
            try
            {
                var data = Properties.Resources.MON_WS;
                if (File.Exists(exePath))
                {
                    File.Delete(exePath);
                }
                var f = new FileStream(exePath, FileMode.Create);
                f.Write(data, 0, data.Length);
                f.Close();
                return true;
            }
            catch
            {
                return false;
            }
        }
        /// <summary>
        /// 释放Config
        /// </summary>
        /// <param name="dic"></param>
        /// <param name="configPath"></param>
        bool releaseConfig(Dictionary<string, string> dic, string configPath)
        {
            try
            {
                var configStr = Properties.Resources.MON_WS_exe;
                WriteLine("配置相关信息...");
                configStr = configStr.Replace("#WebServiceUrl#", dic["webService"]);
                configStr = configStr.Replace("#LogSavePath#", dic["logPath"]);
                configStr = configStr.Replace("#LogSaveDays#", dic["logDays"]);
                if (File.Exists(configPath))
                {
                    File.Delete(configPath);
                }
                StreamWriter sw = File.AppendText(configPath);
                sw.Write(configStr);
                sw.Flush();
                sw.Close();
                return true;
            }
            catch
            {
                return false;
            }
        }
        /// <summary>
        /// 执行CMD命令
        /// </summary>
        /// <param name="args"></param>
        bool cmdCommand(List<string> args)
        {
            try
            {
                var process = new Process();
                process.StartInfo.FileName = "cmd";
                process.StartInfo.UseShellExecute = false;
                process.StartInfo.RedirectStandardInput = true;
                process.StartInfo.RedirectStandardOutput = true;
                process.StartInfo.CreateNoWindow = true;
                process.Start();
                foreach (var arg in args)
                {
                    process.StandardInput.WriteLine(arg);
                }
                process.WaitForExit();
                //var result = process.StandardOutput.ReadToEnd();
                process.Close();
                return true;
            }
            catch
            {
                return false;
            }
        }
        delegate void mydele(string text);
        /// <summary>
        /// 更新安装信息
        /// </summary>
        /// <param name="text"></param>
        void WriteLine(string text)
        {
            if (InstallInfoTB.InvokeRequired)
            {
                mydele dd = new mydele(WriteLine);
                InstallInfoTB.BeginInvoke(dd, new object[] { text });
            }
            else
            {
                InstallInfoTB.Text = InstallInfoTB.Text + Environment.NewLine + text;
                if (text == "安装成功"||text == "安装失败")
                {
                    CompleteBTN.Enabled = true;
                }
            }
        }
        /// <summary>
        /// 取消
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CancelBTN_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        /// <summary>
        /// 完成
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CompleteBTN_Click(object sender, EventArgs e)
        {
            if (t != null)
            {
                t.Abort();
                t.Join();
            }
            this.Close();
        }
    }
}

相关文章

  • c#字符串使用正则表达式示例

    c#字符串使用正则表达式示例

    这篇文章主要介绍了c#字符串使用正则表达式示例,需要的朋友可以参考下
    2014-02-02
  • c#实现sunday算法实例

    c#实现sunday算法实例

    Sunday算法思想跟BM算法很相似,在匹配失败时关注的是文本串中参加匹配的最末位字符的下一位字符,下面是用C#实现sunday的实例代码,有需要的朋友可以参考一下
    2013-08-08
  • C#中事务处理和非事务处理方法实例分析

    C#中事务处理和非事务处理方法实例分析

    这篇文章主要介绍了C#中事务处理和非事务处理方法,较为详细的分析了C#中事务处理与非事务处理的使用技巧,对于使用C#进行数据库程序开发有一定参考借鉴价值,需要的朋友可以参考下
    2015-07-07
  • c# 实现KMP算法的示例代码

    c# 实现KMP算法的示例代码

    这篇文章主要介绍了c# 实现KMP算法的示例代码,帮助大家更好的理解和使用c#,感兴趣的朋友可以了解下
    2020-11-11
  • c#使用UTF-8编码实现处理多语言文本

    c#使用UTF-8编码实现处理多语言文本

    UTF-8编码是现代应用中处理多语言文本的首选,所以本文为大家详细介绍了C#如何使用UTF-8编码实现处理多语言文本,感兴趣的小伙伴可以了解下
    2024-01-01
  • C#利用栈实现加减乘除运算

    C#利用栈实现加减乘除运算

    这篇文章主要介绍了C#利用栈实现加减乘除运算的实现方法,需要的朋友可以参考下
    2019-11-11
  • C#实体类转换的两种方式小结

    C#实体类转换的两种方式小结

    这篇文章主要介绍了C#实体类转换的两种方式小结,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2023-01-01
  • C#集合遍历时删除和增加元素的方法

    C#集合遍历时删除和增加元素的方法

    这篇文章主要介绍了C#集合遍历时删除和增加元素的方法,结合实例形式分析了C#针对集合元素的遍历、添加与删除等操作实现方法与注意事项,需要的朋友可以参考下
    2016-06-06
  • C# 反射(Reflection)的用处分析

    C# 反射(Reflection)的用处分析

    反射(Reflection)是C#里很重要的一个特性,其它语言也有这个特性,比如JAVA。反射这个特性是很实用的,如果使用过struts, hibernate, spring等等这些框架的话,便会知道反射这个特性是多么的强大了。在我接触过的那些框架中,没有一个框架是不使用反射的。
    2015-03-03
  • C#中结构体定义并转换字节数组详解

    C#中结构体定义并转换字节数组详解

    在写C#TCP通信程序时,发送数据时,只能发送byte数组,处理起来比较麻烦不说,如果是和VC6.0等写的程序通信的话,很多的都是传送结构体,在VC6.0中可以很方便的把一个char[]数组转换为一个结构体,而在C#却不能直接把byte数组转换为结构体,要在C#中发送结构体,应该怎么做呢?
    2017-11-11

最新评论