c#制作类似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();
        }
    }
}

(0)

相关推荐

  • C#中载入界面的常用方法

    本文实例讲述了C#中载入界面的常用方法.分享给大家供大家参考.具体方法分析如下: 方法1.采用事件委托的方法  对象:主窗体:FrmMain 加载窗体:FrmLoading  思路:  在主窗体加载前显示窗体FrmLoading,当主窗体加载完毕后(第一次显示的时候),关闭FrmLoading C#代码如下所示: 复制代码 代码如下: using System; using System.Collections.Generic; using System.ComponentModel; usin

  • c#调用qq邮箱smtp发送邮件修改版代码分享

    复制代码 代码如下: try            {                MailMessage mm = new MailMessage();                MailAddress Fromma = new MailAddress("xxxx@qq.com");                MailAddress Toma = new MailAddress("MMMMMMM@qq.com", null);              

  • C#编程实现QQ界面的方法

    本文实例讲述了C#编程实现QQ界面的方法.分享给大家供大家参考,具体如下: 步骤: 1.新建一个页面,假如说叫VerticalMenu 2.把html代码copy到html代码区 3.把LoadTopMenu方法copy到cs代码区 4.运行即可 1.html代码 <STYLE type="text/css"> A:link {}{ COLOR: #000000; FONT-SIZE: 12px; TEXT-DECORATION: none} A:visited {}{ C

  • C#实现简单的登录界面

    首先我们来看一个简单的制作过程 打开visual 2010,新建窗体,既然是登录窗口,那么就不让它出现最大化.最小化以及拖拉大小功能(上一节已经提到过怎么设置大小),如图所示,甚至窗体的Text属性值为"登录窗口",大小随意. 创建窗体之后就开始界面详细的组件布局了,主要是在左边拖拉控件,然后放到窗体中去,定义属性值.这些都比较简单. 到了代码响应阶段,双击登录按钮,进入代码视图: private void button1_Click(object sender, EventArgs

  • C#开发Windows服务实例之实现禁止QQ运行

    本实例主要实现下面三个基本功能 1.C#开发windows服务 2.禁止QQ等程序运行 3.为windows服务创建自动安装程序 下面针对这三个基本功能进行实现 一.C#开发windows服务 Windows服务在VS以前的版本中叫NT服务,在VS.NET启用了新的名称.用C#创建windows服务不是一件困难的事,下页针对服务创建.启动.停止做详细介绍 1.首先在vs中添加一winform程序KillService 2.在解决方案添加新项中添加Windows服务 3.打开服务页面,切换至代码页

  • C#中使用IrisSkin2.dll美化WinForm程序界面的方法

    一.添加控件IrisSkin2.dll.方法:        1.右键"工具箱"."添加选项卡",取名"皮肤".        2.右键"皮肤","选择项"弹出对话框        3.点击"浏览",找到IrisSkin2.dll,,next,next,确定.        4.在皮肤里会出现.        5.把SkinEngine拖到设计界面,会出现在下面. 二,把皮肤文件中以ss

  • C#实现类似qq的屏幕截图程序

    因为近来想写个类似于远程桌面监控的程序,该程序中要用到屏幕捕捉.为实现该程序的一部分功能,做了个小DEMO.程序很简单,用到的技术也不多,只能实现类似qq的截图功能(方法虽然很笨)程序流程如下: 1.截取整个屏幕并保存2.新开一个全屏窗口,将保存的屏幕作为背景3.鼠标拖动改变截取范围,右键取消4.双击截取,保存在粘贴板,全屏窗口关闭 好了,下面的是代码部分 首先新建一个项目ScreenCutter(VS2005),将窗体名改为MainForm,再新建一个窗体ScreenBody.添加一个按钮bt

  • C#截图程序类似腾讯QQ截图实现代码

    最近把以前制作的截图程序重新写了一下动了一个大手术 高质量仿照的TX的截图程序 先看几个效果图 拖动过程中显示当前鼠标下一小块的图像信息 尺寸.颜色信息的  注意 这里颜色是用的ARGB 本来截图的话RGB就够了 可是我把那个做成了控件 不仅截图可用 其他地方也可用作图像的选取 具体看代码就知道了 并且我还加了一个可以截图的同时把鼠标也捕获下来 现在看到的是我自己的截图程序 那个工具条啥的 是从TX的截图程序上面拔下来的 上面是几个工具条上的工具的三种粗细型号的展示 看到的蓝色的粗的刷笔 本来想

  • C#定制Excel界面并实现与数据库交互的方法

    Excel是微软办公套装软件的一个重要的组成部分,它可以进行各种数据的处理.统计分析和辅助决策操作,广泛地应用于管理.统计财经.金融等众多领域.(另外,Excel还是伦敦一所会展中心的名称)..NET可以创建Excel Add-In对Excel进行功能扩展,这些扩展的功能包括自定义用户函数,自定义UI,与数据库进行数据交互等. 一 主要的Excel开发方式 1 VBA VBA是一种Visual Basic的宏语言,它是最早的Office提供定制化的一种解决方案,VBA是VB的一个子集,和Visu

  • C#读取QQ纯真IP数据库QQWry.Dat的代码

    纯真版QQ IP数据库 复制代码 代码如下: using System; using System.Collections.Generic; using System.Text; using System.IO; using System.Web; using System.Configuration; namespace BLL { public class IPLocationSearch { private static readonly QQWry qq = new QQWry(Conf

  • c#调用存储过程实现登录界面详解

    1,创建存储过程 复制代码 代码如下: create proc Pro_Login(@UserName nvarchar(10),@PassWord nvarchar(10))as select * from [User] UserName=@UserName and PassWord=@PassWord 2,通过类是实现配置数据库字符串连接 复制代码 代码如下: class ConnectionString{public static string conStr = "Data Source=

  • C#多线程与跨线程访问界面控件的方法

    本文实例讲述了C#多线程与跨线程访问界面控件的方法.分享给大家供大家参考.具体分析如下: 在编写WinForm访问WebService时,常会遇到因为网络延迟造成界面卡死的现象.启用新线程去访问WebService是一个可行的方法. 典型的,有下面的启动新线程示例: 复制代码 代码如下: private void LoadRemoteAppVersion()  {      if (FileName.Text.Trim() == "") return;      StatusLabel

  • C#中如何使用Winform实现炫酷的透明动画界面

    做过.NET Winform窗体美化的人应该都很熟悉UpdateLayeredWindow吧,UpdateLayeredWindow可以实现窗体的任意透明,效果很好,不会有毛边.不过使用这个API之后,会有一个问题就是无法使用普通控件,而且没有Paint消息.为了解决这个问题,有两种方法. 一.使用双层窗体,底层窗体使用UpdateLayeredWindow作为背景,上层窗体用普通窗体,并且可以使用TransparencyKey或者Region来实现去除不需要的窗体内容,让上层窗体能看到底层的窗

随机推荐