梦想离我很近

VS2003 公共语言调试服务

using System;
using System.Collections;
using System.Windows.Forms;
using System.Data;
using System.IO;
using System.Text;
using System.Diagnostics;
using MySql.Data.MySqlClient;
using ICSharpCode.SharpZipLib.Checksums;
using ICSharpCode.SharpZipLib.Zip;
using ICSharpCode.SharpZipLib.Zip.Compression;
using ICSharpCode.SharpZipLib.Zip.Compression.Streams;
using Microsoft.Win32;
//using IWshRuntimeLibrary;
//using NetFwTypeLib;
using System.Runtime.InteropServices;

namespace InStall
{
 /// <summary>
 /// Form1 的摘要说明。
 /// </summary>
 public class Form1 : System.Windows.Forms.Form
 {  
  [DllImport("kernel32")]
  public static extern void GetWindowsDirectory(StringBuilder SysDir, int count);
  #region
  private System.Windows.Forms.GroupBox groupBox1;
  private System.Windows.Forms.Label label1;
  private System.Windows.Forms.TextBox textBox1;
  private System.Windows.Forms.FolderBrowserDialog folderBrowserDialog1;
  private System.Windows.Forms.Button btnOK;
  private System.Windows.Forms.Button btnClose;
  private System.Windows.Forms.GroupBox groupBox2;
  private System.Windows.Forms.RichTextBox richTextBox1;
  private System.Windows.Forms.Button btnView;
  private System.Windows.Forms.ProgressBar progressBar1;
  private System.Windows.Forms.StatusBar statusBar1;
  private System.Windows.Forms.StatusBarPanel statusBarPanel1;
  /// <summary>
  /// 必需的设计器变量。
  /// </summary>
  private System.ComponentModel.Container components = null;

  public Form1()
  {
   //
   // Windows 窗体设计器支持所必需的
   //
   InitializeComponent();

   //
   // TODO: 在 InitializeComponent 调用后添加任何构造函数代码
   //
   this.statusBar1.Controls.Add(this.progressBar1);
   this.progressBar1.Dock=DockStyle.Fill;
   
  }

  /// <summary>
  /// 清理所有正在使用的资源。
  /// </summary>
  protected override void Dispose( bool disposing )
  {
   if( disposing )
   {
    if (components != null)
    {
     components.Dispose();
    }
   }
   base.Dispose( disposing );
  }

  #region Windows 窗体设计器生成的代码
  /// <summary>
  /// 设计器支持所需的方法 - 不要使用代码编辑器修改
  /// 此方法的内容。
  /// </summary>
  private void InitializeComponent()
  {
   System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(Form1));
   this.groupBox1 = new System.Windows.Forms.GroupBox();
   this.btnView = new System.Windows.Forms.Button();
   this.textBox1 = new System.Windows.Forms.TextBox();
   this.label1 = new System.Windows.Forms.Label();
   this.folderBrowserDialog1 = new System.Windows.Forms.FolderBrowserDialog();
   this.btnOK = new System.Windows.Forms.Button();
   this.btnClose = new System.Windows.Forms.Button();
   this.groupBox2 = new System.Windows.Forms.GroupBox();
   this.richTextBox1 = new System.Windows.Forms.RichTextBox();
   this.progressBar1 = new System.Windows.Forms.ProgressBar();
   this.statusBar1 = new System.Windows.Forms.StatusBar();
   this.statusBarPanel1 = new System.Windows.Forms.StatusBarPanel();
   this.groupBox1.SuspendLayout();
   this.groupBox2.SuspendLayout();
   ((System.ComponentModel.ISupportInitialize)(this.statusBarPanel1)).BeginInit();
   this.SuspendLayout();
   //
   // groupBox1
   //
   this.groupBox1.Controls.Add(this.btnView);
   this.groupBox1.Controls.Add(this.textBox1);
   this.groupBox1.Controls.Add(this.label1);
   this.groupBox1.Dock = System.Windows.Forms.DockStyle.Top;
   this.groupBox1.Location = new System.Drawing.Point(0, 0);
   this.groupBox1.Name = "groupBox1";
   this.groupBox1.Size = new System.Drawing.Size(434, 40);
   this.groupBox1.TabIndex = 0;
   this.groupBox1.TabStop = false;
   //
   // btnView
   //
   this.btnView.Location = new System.Drawing.Point(344, 12);
   this.btnView.Name = "btnView";
   this.btnView.TabIndex = 2;
   this.btnView.Text = "浏览";
   this.btnView.Click += new System.EventHandler(this.btnView_Click);
   //
   // textBox1
   //
   this.textBox1.Location = new System.Drawing.Point(112, 13);
   this.textBox1.Name = "textBox1";
   this.textBox1.Size = new System.Drawing.Size(208, 21);
   this.textBox1.TabIndex = 1;
   this.textBox1.Text = "C:\\fitech\\FitDRS4.0";
   //
   // label1
   //
   this.label1.Location = new System.Drawing.Point(8, 14);
   this.label1.Name = "label1";
   this.label1.TabIndex = 0;
   this.label1.Text = "选择V4.0目录";
   this.label1.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
   //
   // btnOK
   //
   this.btnOK.Location = new System.Drawing.Point(248, 264);
   this.btnOK.Name = "btnOK";
   this.btnOK.TabIndex = 1;
   this.btnOK.Text = "确定(&E)";
   this.btnOK.Click += new System.EventHandler(this.btnOK_Click);
   //
   // btnClose
   //
   this.btnClose.DialogResult = System.Windows.Forms.DialogResult.Cancel;
   this.btnClose.Location = new System.Drawing.Point(336, 264);
   this.btnClose.Name = "btnClose";
   this.btnClose.TabIndex = 2;
   this.btnClose.Text = "退出(&C)";
   this.btnClose.Click += new System.EventHandler(this.btnClose_Click);
   //
   // groupBox2
   //
   this.groupBox2.Controls.Add(this.richTextBox1);
   this.groupBox2.Location = new System.Drawing.Point(0, 40);
   this.groupBox2.Name = "groupBox2";
   this.groupBox2.Size = new System.Drawing.Size(432, 216);
   this.groupBox2.TabIndex = 3;
   this.groupBox2.TabStop = false;
   this.groupBox2.Text = "V5.0新特点";
   //
   // richTextBox1
   //
   this.richTextBox1.Dock = System.Windows.Forms.DockStyle.Fill;
   this.richTextBox1.Location = new System.Drawing.Point(3, 17);
   this.richTextBox1.Name = "richTextBox1";
   this.richTextBox1.ReadOnly = true;
   this.richTextBox1.Size = new System.Drawing.Size(426, 196);
   this.richTextBox1.TabIndex = 0;
   this.richTextBox1.Text = "";
   //
   // progressBar1
   //
   this.progressBar1.Location = new System.Drawing.Point(64, 272);
   this.progressBar1.Maximum = 10;
   this.progressBar1.Name = "progressBar1";
   this.progressBar1.Size = new System.Drawing.Size(144, 8);
   this.progressBar1.TabIndex = 4;
   //
   // statusBar1
   //
   this.statusBar1.Location = new System.Drawing.Point(0, 297);
   this.statusBar1.Name = "statusBar1";
   this.statusBar1.Panels.AddRange(new System.Windows.Forms.StatusBarPanel[] {
                        this.statusBarPanel1});
   this.statusBar1.ShowPanels = true;
   this.statusBar1.Size = new System.Drawing.Size(434, 22);
   this.statusBar1.SizingGrip = false;
   this.statusBar1.TabIndex = 5;
   this.statusBar1.Text = "statusBar1";
   //
   // statusBarPanel1
   //
   this.statusBarPanel1.Text = "statusBarPanel1";
   this.statusBarPanel1.Width = 434;
   //
   // Form1
   //
   this.AcceptButton = this.btnOK;
   this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);
   this.CancelButton = this.btnClose;
   this.ClientSize = new System.Drawing.Size(434, 319);
   this.Controls.Add(this.statusBar1);
   this.Controls.Add(this.progressBar1);
   this.Controls.Add(this.groupBox2);
   this.Controls.Add(this.btnClose);
   this.Controls.Add(this.btnOK);
   this.Controls.Add(this.groupBox1);
   this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
   this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
   this.MaximizeBox = false;
   this.Name = "Form1";
   this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
   this.Text = "银监会数据采集系统客户端V4.0升级V5.0";
   this.Load += new System.EventHandler(this.Form1_Load);
   this.groupBox1.ResumeLayout(false);
   this.groupBox2.ResumeLayout(false);
   ((System.ComponentModel.ISupportInitialize)(this.statusBarPanel1)).EndInit();
   this.ResumeLayout(false);

  }
  #endregion
  #endregion
  /// <summary>
  /// 应用程序的主入口点。
  /// </summary>
  [STAThread]
  static void Main()
  {  
   Application.EnableVisualStyles();
   //Application.DoEvents();
   Application.Run(new Form1());
  }
  private void Form1_Load(object sender, System.EventArgs e)
  {
   this.richTextBox1.Text="          银监会数据采集系统客户端从V4.0升级到5.0    "+Environment.NewLine;
   this.richTextBox1.Text+="—————————————————————————————————"+Environment.NewLine;
   this.richTextBox1.Text+="1.模板版本升级到最新的1110版本,原0690,0810,0910,1010版本继续兼容"+Environment.NewLine;
   this.richTextBox1.Text+="2.2011年第一阶段升级报表,详见如下:"+Environment.NewLine;
   this.richTextBox1.Text+="  法人报表: G0109,G1103,G1401,G1402,G1403"+Environment.NewLine;
   this.richTextBox1.Text+="             S3a00,S3e00,S3f00,S3j00,S3k00"+Environment.NewLine;
   this.richTextBox1.Text+="             S3m00,S3205,S3900,S4100,S4200"+Environment.NewLine;
   this.richTextBox1.Text+="             S4400,S4500,S4700,S6200"+Environment.NewLine;
   this.richTextBox1.Text+="  分支报表: GF0109,GF1103,GF1401,GF1403,SF6200"+Environment.NewLine;
   this.richTextBox1.Text+="  "+Environment.NewLine;   

  }

  private void btnView_Click(object sender, System.EventArgs e)
  {
   folderBrowserDialog1=new FolderBrowserDialog();
   if(folderBrowserDialog1.ShowDialog()==DialogResult.OK)
   {
    this.textBox1.Text=folderBrowserDialog1.SelectedPath;   
   }
  }
  private void btnClose_Click(object sender, System.EventArgs e)
  {
   this.Close();
  }
  /// <summary>
  /// 判断客户端是否在运行
  /// </summary>
  /// <returns>true or false</returns>
  private bool IsRun()
  {  
   bool isExist=false;
   Process []p=System.Diagnostics.Process.GetProcesses();
   for(int i=0;i<p.Length;i++)
   {
    if(p[i].ProcessName.ToUpper()=="FITDRS")
    {
      isExist=true;
      break;
    }
   
   }
   return isExist;  
  }
  private void btnOK_Click(object sender, System.EventArgs e)
  {  
   this.Cursor = System.Windows.Forms.Cursors.WaitCursor;
   this.btnOK.Enabled=false;
   progressBar1.Value=0;
   if(this.textBox1.Text.Trim()==string.Empty)
   {
    MessageBox.Show("请选择客户端V4.0安装目录","提示",MessageBoxButtons.OK,MessageBoxIcon.Information);
    this.btnView.Focus();    
    this.Cursor = System.Windows.Forms.Cursors.Default;
    progressBar1.Value=0;
    this.btnOK.Enabled=true;
    return;
   }
   string path=this.textBox1.Text;   
   if(!Directory.Exists(path))
   {
    MessageBox.Show("请选择客户端V4.0安装目录不存在","警告",MessageBoxButtons.OK,MessageBoxIcon.Information);
    this.btnView.Focus();
    this.Cursor = System.Windows.Forms.Cursors.Default;
    progressBar1.Value=0;
    this.btnOK.Enabled=true;
    return;
   }
   if(IsRun())
   {  
    MessageBox.Show("升级时请关闭客户端!","提示",MessageBoxButtons.OK,MessageBoxIcon.Information);
    this.Cursor = System.Windows.Forms.Cursors.Default;
    this.btnOK.Enabled=true;
    progressBar1.Value=0;
    return;
   }   
   string rootPath  = Application.StartupPath;
   //string rootPath  = System.Environment.CurrentDirectory;   
   string []keyStr  = new string[]{"FTExcelDocument.DLL","MySql.Data.DLL","DRS_Reg.dll"};
   string []fileList=Directory.GetFiles(path);
   string fileName=string.Empty;
   int counter=0;
   for(int i=0;i<fileList.Length;i++)
   {
    fileName=Path.GetFileName(fileList[i]);
    for(int j=0;j<keyStr.Length;j++)
    {
     if(fileName.ToLower()==keyStr[j].ToLower())
     {
      counter++;
      break;
     }
    }     
   }
   progressBar1.Value++;
   if(counter!=keyStr.Length)
   {
    MessageBox.Show("你选择的V4.0安装目录不正确,请重新选择","警告",MessageBoxButtons.OK,MessageBoxIcon.Information);
    this.btnView.Focus();
    this.Cursor = System.Windows.Forms.Cursors.Default;
    this.btnOK.Enabled=true;
    progressBar1.Value=0;
    return;    
   }
   //添加应用程序到防火墙中
   //AddAppToFireWall(path);
   //验证当前客户端版本
   int flag=ValVersion();
   if(flag==0)
   {  
    this.Cursor = System.Windows.Forms.Cursors.Default;
    progressBar1.Value=0;
    this.btnOK.Enabled=true;
    return;
   }
   if(flag==2)
   {  
    this.Cursor = System.Windows.Forms.Cursors.Default;
    progressBar1.Value=0;
    this.btnOK.Enabled=true;
    return;
   }
   if(flag==-1)
   {
    MessageBox.Show("你当前客户端版本是V5.0,不需更新","提示",MessageBoxButtons.OK,MessageBoxIcon.Information);
    this.Cursor = System.Windows.Forms.Cursors.Default;
    this.btnOK.Enabled=true;
    progressBar1.Value=0;
    return;
   }
   string fileZip    =rootPath+"\\V5.0.zip";
   string tempfileZip=rootPath+"\\V5.0temp.zip";
   string tempfileDir=rootPath+"\\temp\\";
   //当数据文件不存在时。
   if(!System.IO.File.Exists(fileZip))
   {  
                MessageBox.Show(fileZip,"警告",MessageBoxButtons.OK,MessageBoxIcon.Information);
    MessageBox.Show("升级文件V5.0.zip不存在","警告",MessageBoxButtons.OK,MessageBoxIcon.Information);
    this.btnView.Focus();
    this.Cursor = System.Windows.Forms.Cursors.Default;
    this.btnOK.Enabled=true;
    progressBar1.Value=0;
    return;
   }
   //解密数据升级文件
   if(!addkeyWord(fileZip,tempfileZip))
   {
    MessageBox.Show("释放升级文件V5.0.zip失败","警告",MessageBoxButtons.OK,MessageBoxIcon.Information);
    this.btnView.Focus();
    this.Cursor = System.Windows.Forms.Cursors.Default;
    this.btnOK.Enabled=true;
    progressBar1.Value=0;
    return;    
   }
   //解压Zip文件
   if(!UnZip(new string[]{tempfileZip,tempfileDir}))
   {  
    MessageBox.Show("释放升级文件temp.zip失败","警告",MessageBoxButtons.OK,MessageBoxIcon.Information);
    this.btnView.Focus();
    this.Cursor = System.Windows.Forms.Cursors.Default;
    this.btnOK.Enabled=true;
    progressBar1.Value=0;
    return; 
   }   
   System.IO.File.Delete(tempfileZip);
   rootPath=tempfileDir;
   //pdfdata文件夹路径
   string pdPath=string.Empty;
   //pdftemp文件夹路径
   string ptPath=string.Empty;
   //更新文件路径     
   string exeName   =string.Empty;
   string itextName =string.Empty;
   string peName    =string.Empty;
   string pcName    =string.Empty;
   string xmlName   =string.Empty;
   string dexeName  =string.Empty;
   string ditextName=string.Empty;
   string dpeName   =string.Empty;
   string dpcName   =string.Empty;
   string dxmlName  =string.Empty;
   string dbpath    =string.Empty;
   string uninstall =string.Empty;
   string duninstall=string.Empty;
   string des_Reg=string.Empty;
   string ddes_Reg=string.Empty;
   bool isTrue=false; 
   progressBar1.Value++; 
   #region
   try
   {  
    pdPath=path+"\\pdfdata";
    ptPath=path+"\\pdftemp";
    DirectoryInfo di=new DirectoryInfo(pdPath);
    if(!Directory.Exists(pdPath))
     di.Create();
    di=new DirectoryInfo(ptPath);
    if(!Directory.Exists(ptPath))
     di.Create();
    exeName   =rootPath+"\\FitDRS.exe";
    itextName =rootPath+"\\itextsharp.dll";
    peName    =rootPath+"\\FTExcelDocument.dll";
    pcName    =rootPath+"\\PConvert.dll";
    xmlName   =rootPath+"\\xmlDbConnector.xml";
    uninstall =rootPath+"\\UnInstall.exe";
    des_Reg   =rootPath+"\\DRS_Reg.dll";
    dexeName  =path+"\\FitDRS.exe";
    ditextName=path+"\\itextsharp.dll";
    dpeName   =path+"\\FTExcelDocument.dll";
    dpcName   =path+"\\PConvert.dll";
    dxmlName  =path+"\\common\\config"+"\\"+"xmlDbConnector.xml";
    duninstall=path+"\\UnInstall.exe";
    ddes_Reg  =path+"\\DRS_Reg.dll";
    if((!System.IO.File.Exists(exeName))||(!System.IO.File.Exists(itextName))||(!System.IO.File.Exists(peName))||(!System.IO.File.Exists(pcName)))
    {
     MessageBox.Show("你下载的更新程序不全,请重新下载","警告",MessageBoxButtons.OK,MessageBoxIcon.Information);
     this.btnView.Focus();
     this.Cursor = System.Windows.Forms.Cursors.Default;
     this.btnOK.Enabled=true;
     return;
    }
    progressBar1.Value++;  
    //修改快捷方式
    UpdateShortCuts(path);     
    System.IO.File.Copy(exeName,dexeName,true);
    System.IO.File.Copy(itextName,ditextName,true);
    System.IO.File.Copy(peName,dpeName,true);
    System.IO.File.Copy(pcName,dpcName,true);
    System.IO.File.Copy(uninstall,duninstall,true);
    System.IO.File.Copy(des_Reg,ddes_Reg,true);
    progressBar1.Value++;
    //20101120 youxiaoliang start
    //System.IO.File.Copy(xmlName,dxmlName,true);
    //20101120 youxiaoliang end
    dbpath=rootPath;
    string []dbfile=Directory.GetFiles(dbpath);
    string ddbfile=path+"\\mysql\\data\\clientdb\\";
    if(!StopMysql())
    {
     MessageBox.Show("你停止MySQL失败","警告",MessageBoxButtons.OK,MessageBoxIcon.Information);
     this.btnView.Focus();
     this.Cursor = System.Windows.Forms.Cursors.Default;
     this.btnOK.Enabled=true;
     return;
    }
    string dbfileName=string.Empty;
    for(int j=0;j<dbfile.Length;j++)
    {  
     dbfileName=Path.GetFileName(dbfile[j]);
     if(dbfileName=="FitDRS.exe"||dbfileName=="itextsharp.dll"||dbfileName=="FTExcelDocument.dll"||dbfileName=="PConvert.dll"||dbfileName=="xmlDbConnector.xml"||dbfileName=="DRS_Reg.dll"||dbfileName=="UnInstall.exe")
      continue;
     System.IO.File.Copy(dbfile[j],ddbfile+Path.GetFileName(dbfile[j]),true);
    }      
    if(StartMysql())
    {    
     if(ExexSQL(rootPath))
     { 
      isTrue=true;
     }
     else
     {
      isTrue=false;
     }
     progressBar1.Value++; 
    }
    else
    {
     MessageBox.Show("启动MySQL服务失败","警告",MessageBoxButtons.OK,MessageBoxIcon.Information);
     this.btnView.Focus();
     this.Cursor = System.Windows.Forms.Cursors.Default;
     this.btnOK.Enabled=true;
     return;
    }
   }
   catch(IOException ioex)
   {
    MessageBox.Show(ioex.Message,"警告",MessageBoxButtons.OK,MessageBoxIcon.Information);
    MessageBox.Show(ioex.StackTrace,"警告",MessageBoxButtons.OK,MessageBoxIcon.Information);
    MessageBox.Show(ioex.ToString(),"警告",MessageBoxButtons.OK,MessageBoxIcon.Information);
    this.btnView.Focus();
    this.Cursor = System.Windows.Forms.Cursors.Default;
    this.btnOK.Enabled=true;
    return;
   }
   catch(Exception ex)
   {
    MessageBox.Show(ex.Message,"警告",MessageBoxButtons.OK,MessageBoxIcon.Information);
    this.btnView.Focus();
    this.Cursor = System.Windows.Forms.Cursors.Default;
    this.btnOK.Enabled=true;
    return;
   }
   #endregion
   if(isTrue)
   {  
    //当更新成功
    //UpdateInstallDir(path);              
    if(Directory.Exists(tempfileDir))
    {
        string []tfileName=Directory.GetFiles(tempfileDir);
     for(int n=0;n<tfileName.Length;n++)
     {
       System.IO.File.Delete(tfileName[n]);
     }
     Directory.Delete(tempfileDir);
    }    
    progressBar1.Value++;
    MessageBox.Show("你已经成功升级到V5.0","提示",MessageBoxButtons.OK,MessageBoxIcon.Information);
   }
   else
   {  
    if(Directory.Exists(tempfileDir))
    {
        string []tfileName=Directory.GetFiles(tempfileDir);
     for(int n=0;n<tfileName.Length;n++)
     {
       System.IO.File.Delete(tfileName[n]);
     } 
     Directory.Delete(tempfileDir);
    } 
    MessageBox.Show("你升级失败","警告",MessageBoxButtons.OK,MessageBoxIcon.Information);
   }
   this.Cursor = System.Windows.Forms.Cursors.Default;
   this.btnOK.Enabled=true;
   
  }
//        /// <summary>
//        /// 添加应用程序到防火墙中
//        /// </summary>
//        /// <param name="path">应用程序路径</param>
//  private void AddAppToFireWall(string path)
//  {
//     string appPath=path+"\\mysql\\bin\\mysqld-nt.exe";
//   try
//   {
//    //创建firewall管理类的实例
//    INetFwMgr netFwMgr = (INetFwMgr)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FwMgr"));
//
//    //创建一个认证程序类的实例
//    INetFwAuthorizedApplication app = (INetFwAuthorizedApplication)Activator.CreateInstance(
//     Type.GetTypeFromProgID("HNetCfg.FwAuthorizedApplication"));
//
//    //在例外列表里,程序显示的名称
//    app.Name = "MySQL";
//
//    //程序的决定路径,这里使用程序本身
//    app.ProcessImageFileName = appPath;
//
//    //是否启用该规则
//    app.Enabled = true;
//    //加入到防火墙的管理策略
//    try
//    {
//     INetFwAuthorizedApplication  appName=netFwMgr.LocalPolicy.CurrentProfile.AuthorizedApplications.Item(appPath);
//    }
//    catch
//    {
//      netFwMgr.LocalPolicy.CurrentProfile.AuthorizedApplications.Add(app);
//    }    
//   }
//   catch(COMException comex)
//   {
//      string ex1=comex.Message;
//   }
//   catch(Exception ex)
//   {
//     string ex2=ex.Message;
//   }  
//  
//  }
  /// <summary>
  /// 更新安装目录
  /// </summary>
  /// <param name="path">安装路径</param>
  private void UpdateInstallDir(string path)
  {  
   try
   {  
    if(!StopMysql())
     return;
                if(!UnInstallMySQL())
     return;
    int lastIndex=path.LastIndexOf("\\");
    string newDir=path.Substring(0,lastIndex);
    newDir+="\\FitDRS5.0";
    Directory.Move(path,newDir);
    CreateShortCuts(newDir);
   }
   catch(Exception ex)
   {
       MessageBox.Show(ex.Message);
   }  
  }
  /// <summary>
  /// 创建快捷方式
  /// </summary>
  /// <param name="path"></param>
  private void CreateShortCuts(string path)
  {  
   try
   {
    string oldPath  ="银监会数据采集系统";
    string unoldName="卸载银监会数据采集系统客户端V4.0.lnk";
    string oldName  ="银监会数据采集系统客户端V4.0";
    string unnewName="卸载银监会数据采集系统客户端.lnk";
    string newName  ="银监会数据采集系统客户端";
    //修改开始菜单名称
    //开始菜单
    string startMenu=Environment.GetFolderPath(Environment.SpecialFolder.StartMenu);
    //开始菜单下综合版路径目录
    string shortCuts=startMenu+"\\程序"+"\\"+oldPath;
    string newshortCuts  =shortCuts+"\\"+newName;
    string unnewshortCuts=shortCuts+"\\"+unnewName;
    string oldshortCuts  =shortCuts+"\\"+oldName;
    string unoldshortCuts=shortCuts+"\\"+unoldName;
    string exePath=path+"\\FitDRS.exe";
    string unPath =path+"\\uninstall.exe";
    //if(!CreateShorts(exePath,"",newshortCuts))
    // return;
    //if(!CreateShorts(unPath,"",unnewshortCuts))
    //return;
                UpdateDesktopFileName(oldName,newName);
//    if(System.IO.File.Exists(unoldshortCuts))
//    {  
//     System.IO.File.Move(newshortCuts,oldshortCuts);
//    }
//    if(System.IO.File.Exists(oldshortCuts))
//    {
//     System.IO.File.Move(newshortCuts,oldshortCuts);
//    }
//    //修改桌面快捷方式
//    string deskDir=Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
//    string deskShortCut=deskDir+"\\"+newName;
//    if(System.IO.File.Exists(deskDir+"\\"+oldName))
//    {  
//     System.IO.File.Delete(deskDir+"\\"+oldName);
//     System.IO.File.Copy(newshortCuts,deskShortCut);
//    } 
   }
   catch
   {
   
   }
  
  }
  private void UpdateDesktopFileName(string old_loc,string new_loc)
  {
   string location = "";
   RegistryKey key = Registry.CurrentUser.OpenSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders", true);
   if(key.GetValue("Desktop") !=null)
   {
    location = key.GetValue("Desktop").ToString();
   }

   if(location !="")
   {
    string old_location = location + "\\"+old_loc+".lnk";

    //string new_location = location + "\\"+client.common.Init.SystemTitle+"V"+client.common.Init.SystemVersion+".lnk";
    string new_location = location + "\\"+new_loc+".lnk";

    try
    {
     //修改桌面快捷方式
     if(File.Exists(old_location))
     {
      File.Move(old_location,new_location);
      File.Delete(old_location);

     }
    }
    catch(Exception ex)
    {
     Console.Write(ex.ToString());
    }

   }

   //string fold = "";
   if(key.GetValue("Programs") !=null)
   {
    location = key.GetValue("Programs").ToString();
   }

   if(location !="")
   {
    string old_location = location + "\\银监会数据采集系统";

    //string new_location = location + "\\"+client.common.Init.SystemTitle+"V"+client.common.Init.SystemVersion+".lnk";
    string new_location = location + "\\银监会数据采集系统";

    try
    {
     //修改开始菜单项目
     if(Directory.Exists(old_location))
     {
      //Directory.Move(old_location,new_location);
      //Directory.Delete(old_location);

      string old_loc1 = new_location + "\\"+old_loc+".lnk";
      string new_loc1 = new_location + "\\"+new_loc+".lnk";

      string old_loc2 = new_location + "\\卸载"+old_loc+".lnk";
      string new_loc2 = new_location + "\\卸载"+new_loc+".lnk";

      if(File.Exists(old_loc1))
      {
       File.Move(old_loc1,new_loc1);
       File.Delete(old_loc1);
      }

      if(File.Exists(old_loc2))
      {
       File.Move(old_loc2,new_loc2);
       File.Delete(old_loc2);
      }

     }
     else
     {  
      Directory.CreateDirectory(old_location);
      string old_loc1 = new_location + "\\"+old_loc+".lnk";
      string new_loc1 = new_location + "\\"+new_loc+".lnk";

      string old_loc2 = new_location + "\\卸载"+old_loc+".lnk";
      string new_loc2 = new_location + "\\卸载"+new_loc+".lnk";

      if(File.Exists(old_loc1))
      {
       File.Move(old_loc1,new_loc1);
       File.Delete(old_loc1);
      }

      if(File.Exists(old_loc2))
      {
       File.Move(old_loc2,new_loc2);
       File.Delete(old_loc2);
      }
     }
    }
    catch(Exception ex)
    {
     Console.Write(ex.ToString());
    }

   }

  }
//  /// <summary>
//  /// 创建快捷方式
//  /// </summary>
//  /// <param name="app">应用程序全路径</param>
//  /// <param name="desc">描述</param>
//  /// <param name="fileName">文件名</param>
//  /// <returns>true or false</returns>
//  private bool CreateShorts(string app,string desc,string fileName)
//  {  
//   bool isTrue=false;
//   try
//   {
//    // Create a Windows Script Host Shell class
//    IWshShell_Class shell = new IWshShell_ClassClass();
//    // Define the shortcut file
//    IWshShortcut_Class shortcut = shell.CreateShortcut(fileName) as IWshShortcut_Class;
//    // Set all its properties
//    shortcut.Description  = desc;
//    shortcut.TargetPath   = app;    
//    shortcut.IconLocation = app + ",0";
//    // Save it
//    shortcut.Save();
//                isTrue=true;
//   }
//   catch(COMException ex)
//   {
//    Console.WriteLine(ex.Message);
//   }
//   return isTrue;
//  
//  }
  private void JMZip()
  {
   
  }
  /// <summary>
  /// 卸载MySQL服务
  /// </summary>
  /// <returns>true or false</returns>
  private bool UnInstallMySQL()
  {
   bool isTrue=true;
   System.ServiceProcess.ServiceController[] mysera= System.ServiceProcess.ServiceController.GetServices();
   for(int i=0;i<mysera.Length;i++)
   { 
    if(mysera[i].ServiceName.ToUpper().Length>=5)
    {
     if(mysera[i].ServiceName.ToUpper().Substring(0,5).Equals("MYSQL"))
     {  
        if(CMDLine(string.Format("sc delete {0}",mysera[i].ServiceName)))
        isTrue=true;
        else
           isTrue=false;
        break;
     }
    }
   }
   return isTrue;
  
  }
  /// <summary>
  /// 验证当前的版本是否最新的版本
  /// </summary>
  /// <returns>1 成功 -1 失败 0 MYSQL启动失败</returns>
  private int ValVersion()
  {
   string dsql   =string.Format("SELECT ver FROM fitech_version limit 0,1");
   if(!StartMysql())
   {
      MessageBox.Show("启动MySQL服务失败","警告",MessageBoxButtons.OK,MessageBoxIcon.Warning);
      return 0;
   }
   string version=DB_Class_OneRecord(dsql);
   if(version=="0")
   {
      return 2;
   }
   if(version=="V5.0")
   {
     return -1;    
   }
   return 1;  
  }
  /// <summary>
  /// 修改快捷方式
  /// </summary>
  /// <param name="path">文件执行路径</param>
  private void UpdateShortCuts(string path)
  {
   string oldPath  ="银监会数据采集系统";
   string unoldName="卸载银监会数据采集系统客户端V4.0.lnk";
   string oldName  ="银监会数据采集系统客户端V4.0";
   string unnewName="卸载银监会数据采集系统客户端.lnk";
   string newName  ="银监会数据采集系统客户端";
   //修改开始菜单名称
   //开始菜单
   string startMenu=Environment.GetFolderPath(Environment.SpecialFolder.StartMenu);
   //开始菜单下综合版路径目录
   string shortCuts=startMenu+"\\程序"+"\\"+oldPath;
   if(!System.IO.Directory.Exists(shortCuts))
    System.IO.Directory.CreateDirectory(shortCuts);
   string newshortCuts  =shortCuts+"\\"+newName;
   string unnewshortCuts=shortCuts+"\\"+unnewName;
   string oldshortCuts  =shortCuts+"\\"+oldName;
   string unoldshortCuts=shortCuts+"\\"+unoldName;
   string exePath=path+"\\FitDRS.exe";
   string uninstallPath=path+"\\uninstall.exe";
   try
   {
    UpdateDesktopFileName(oldName,newName);
   }
   catch(Exception ex)
   {
      MessageBox.Show(ex.Message,"警告",MessageBoxButtons.OK,MessageBoxIcon.Warning);
   }
//   if(System.IO.File.Exists(unoldshortCuts))
//   {
//    System.IO.File.Delete(unoldshortCuts);
//   }
//   CreateShorts(uninstallPath,"",unnewshortCuts);
//   if(System.IO.File.Exists(oldshortCuts))
//   {
//    System.IO.File.Delete(oldshortCuts);
//   }
//   CreateShorts(exePath,"",newshortCuts);
//   修改桌面快捷方式
//   string deskDir=Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
//   if(System.IO.File.Exists(deskDir+"\\"+oldName))
//   {
//    System.IO.File.Delete(deskDir+"\\"+oldName);
//   }
      //CreateShorts(exePath,"",deskDir+"\\"+newName);
  }  
  /// <summary>
  /// 更新model_infor report_infor表
  /// </summary>
  /// <param name="rootPath">临时文件夹</param>
  /// <returns>true or false</returns>
  private bool ExexSQL(string rootPath)
  {  
   ArrayList al=new ArrayList();
   #region
   string dmsql=string.Format("delete from model_infor where ModelVersion='1110'");
   al.Add(dmsql);
   string sql1=string.Format("INSERT INTO `clientdb`.`model_infor`(`MainTitle`,`SubTitle`,`ModelID`,`ModelVersion`,`ReportType`,`StartRow`,`DataStart`,`StartCol`)VALUES ('G01资产负债项目统计表附注','第Ⅸ部分:存贷款月日均情况表','G0109','1110','P', 0, 5, 2)");
   string sql2=string.Format("INSERT INTO `clientdb`.`model_infor`(`MainTitle`,`SubTitle`,`ModelID`,`ModelVersion`,`ReportType`,`StartRow`,`DataStart`,`StartCol`)VALUES ('G11资产质量五级分类情况表','第III部分:按行业大类分类的贷款(按贷款投向)','G1103','1110','P', 0, 7, 2)");
   string sql3=string.Format("INSERT INTO `clientdb`.`model_infor`(`MainTitle`,`SubTitle`,`ModelID`,`ModelVersion`,`ReportType`,`StartRow`,`DataStart`,`StartCol`)VALUES ('G14授信集中情况表','第II部分:最大十家金融机构同业授信情况表','G1402','1110','P', 0, 7, 2)");
   string sql4=string.Format("INSERT INTO `clientdb`.`model_infor`(`MainTitle`,`SubTitle`,`ModelID`,`ModelVersion`,`ReportType`,`StartRow`,`DataStart`,`StartCol`)VALUES ('G14授信集中情况表','第III部分:最大十家客户贷款情况表','G1403','1110','P', 0, 7, 2)");
   string sql5=string.Format("INSERT INTO `clientdb`.`model_infor`(`MainTitle`,`SubTitle`,`ModelID`,`ModelVersion`,`ReportType`,`StartRow`,`DataStart`,`StartCol`)VALUES ('G14授信集中情况表','第Ⅰ部分:最大十家集团客户授信情况表','G1401','1110','P', 0, 7, 2)");
   string sql6=string.Format("INSERT INTO `clientdb`.`model_infor`(`MainTitle`,`SubTitle`,`ModelID`,`ModelVersion`,`ReportType`,`StartRow`,`DataStart`,`StartCol`)VALUES ('GF14授信集中情况表','第Ⅰ部分:最大十家集团客户授信情况表','GF1401','1110','P', 0, 7, 2)");
   string sql7=string.Format("INSERT INTO `clientdb`.`model_infor`(`MainTitle`,`SubTitle`,`ModelID`,`ModelVersion`,`ReportType`,`StartRow`,`DataStart`,`StartCol`)VALUES ('GF14授信集中情况表','第III部分:最大十家客户贷款情况表','GF1403','1110','P', 0, 7, 2)");
   string sql8=string.Format("INSERT INTO `clientdb`.`model_infor`(`MainTitle`,`SubTitle`,`ModelID`,`ModelVersion`,`ReportType`,`StartRow`,`DataStart`,`StartCol`)VALUES ('S3j消费金融公司贷款明细分类及其他情况表','S3j消费金融公司贷款明细分类及其他情况表','S3j00','1110','P', 0, 7, 2)");
   string sql9=string.Format("INSERT INTO `clientdb`.`model_infor`(`MainTitle`,`SubTitle`,`ModelID`,`ModelVersion`,`ReportType`,`StartRow`,`DataStart`,`StartCol`)VALUES ('S42农村中小金融机构补充数据表','S42农村中小金融机构补充数据表','S4200','1110','P', 0, 5, 3)");
   string sql0=string.Format("INSERT INTO `clientdb`.`model_infor`(`MainTitle`,`SubTitle`,`ModelID`,`ModelVersion`,`ReportType`,`StartRow`,`DataStart`,`StartCol`)VALUES ('S47新型农村金融机构经营情况统计表','S47新型农村金融机构经营情况统计表','S4700','1110','P', 0, 4, 2)");
   string sql11=string.Format("INSERT INTO `clientdb`.`model_infor`(`MainTitle`,`SubTitle`,`ModelID`,`ModelVersion`,`ReportType`,`StartRow`,`DataStart`,`StartCol`)VALUES ('GF01资产负债项目统计表附注','第Ⅸ部分:存贷款月日均情况表','GF0109','1110','P', 0, 5, 2)");
   string sql12=string.Format("INSERT INTO `clientdb`.`model_infor`(`MainTitle`,`SubTitle`,`ModelID`,`ModelVersion`,`ReportType`,`StartRow`,`DataStart`,`StartCol`)VALUES ('GF11资产质量五级分类情况表','第III部分:按行业大类分类的贷款(按贷款投向)','GF1103','1110','P', 0, 7, 2) ");
   string sql13=string.Format("INSERT INTO `clientdb`.`model_infor`(`MainTitle`,`SubTitle`,`ModelID`,`ModelVersion`,`ReportType`,`StartRow`,`DataStart`,`StartCol`)VALUES ('S3a汽车金融公司贷款质量五级分类情况表','S3a汽车金融公司贷款质量五级分类情况表','S3a00','1110','P', 0, 7, 2)");
   string sql14=string.Format("INSERT INTO `clientdb`.`model_infor`(`MainTitle`,`SubTitle`,`ModelID`,`ModelVersion`,`ReportType`,`StartRow`,`DataStart`,`StartCol`)VALUES ('S3e金融租赁公司租赁业务情况统计表','S3e金融租赁公司租赁业务情况统计表','S3e00','1110','P', 0, 6, 2)");
   string sql15=string.Format("INSERT INTO `clientdb`.`model_infor`(`MainTitle`,`SubTitle`,`ModelID`,`ModelVersion`,`ReportType`,`StartRow`,`DataStart`,`StartCol`)VALUES ('S3f汽车金融公司异地业务情况月报表','S3f汽车金融公司异地业务情况月报表','S3f00','1110','P', 0, 5, 2)");
   string sql16=string.Format("INSERT INTO `clientdb`.`model_infor`(`MainTitle`,`SubTitle`,`ModelID`,`ModelVersion`,`ReportType`,`StartRow`,`DataStart`,`StartCol`)VALUES ('S3k信托公司净资本计算表','S3k信托公司净资本计算表','S3k00','1110','P', 0, 5, 1)");
   string sql17=string.Format("INSERT INTO `clientdb`.`model_infor`(`MainTitle`,`SubTitle`,`ModelID`,`ModelVersion`,`ReportType`,`StartRow`,`DataStart`,`StartCol`)VALUES ('S3m信托公司风险资本计算表','S3m信托公司风险资本计算表','S3m00','1110','P', 0, 5, 1)");
   string sql18=string.Format("INSERT INTO `clientdb`.`model_infor`(`MainTitle`,`SubTitle`,`ModelID`,`ModelVersion`,`ReportType`,`StartRow`,`DataStart`,`StartCol`)VALUES ('S32信托公司管理信托财产状况统计表','补充材料二:信托资金运用行业分类情况','S3205','1110','P', 0, 5, 2)");
   string sql19=string.Format("INSERT INTO `clientdb`.`model_infor`(`MainTitle`,`SubTitle`,`ModelID`,`ModelVersion`,`ReportType`,`StartRow`,`DataStart`,`StartCol`)VALUES ('S39租赁业务资产负债项目统计表','S39租赁业务资产负债项目统计表','S3900','1110','P', 0, 5, 2)");
   string sql20=string.Format("INSERT INTO `clientdb`.`model_infor`(`MainTitle`,`SubTitle`,`ModelID`,`ModelVersion`,`ReportType`,`StartRow`,`DataStart`,`StartCol`)VALUES ('S45农村中小金融机构支农服务情况统计表','S45农村中小金融机构支农服务情况统计表','S4500','1110','P', 0, 4, 3)");
   string sql21=string.Format("INSERT INTO `clientdb`.`model_infor`(`MainTitle`,`SubTitle`,`ModelID`,`ModelVersion`,`ReportType`,`StartRow`,`DataStart`,`StartCol`)VALUES ('S62贷款按“三个办法、一个指引”执行情况表','S62贷款按“三个办法、一个指引”执行情况表','S6200','1110','P', 0, 4, 2)");
   string sql22=string.Format("INSERT INTO `clientdb`.`model_infor`(`MainTitle`,`SubTitle`,`ModelID`,`ModelVersion`,`ReportType`,`StartRow`,`DataStart`,`StartCol`)VALUES ('SF62贷款按“三个办法、一个指引”执行情况表','SF62贷款按“三个办法、一个指引”执行情况表','SF6200','1110','P', 0, 4, 2)");
   al.AddRange(new string[]{sql0,sql1,sql2,sql3,sql4,sql5,sql6,sql7,sql8,sql9,sql11,sql12,sql13,sql14,sql15,sql16,sql17,sql18,sql19,sql20,sql21,sql22});
   string sqlqq=string.Format("DELETE FROM client_user_right WHERE rightID IN (33,34,35,36,37)");
   string sqlpp=string.Format("DELETE FROM client_right WHERE ID IN (33,34,35,36,37)");
   al.AddRange(new string[]{sqlpp,sqlqq});
   string sqla=string.Format("INSERT INTO client_right(ID,description)VALUES(33,'科技风险制度包更新')");
   string sqlb=string.Format("INSERT INTO client_right(ID,description)VALUES(34,'科技风险模板更新')");
   string sqlc=string.Format("INSERT INTO client_right(ID,description)VALUES(35,'科技风险数据填写')");
   string sqld=string.Format("INSERT INTO client_right(ID,description)VALUES(36,'科技风险数据装载')");
   string sqle=string.Format("INSERT INTO client_right(ID,description)VALUES(37,'科技风险数据打包')");
   string sqlf=string.Format("INSERT INTO client_user_right(userID,rightID)VALUES(1,33)");
   string sqlg=string.Format("INSERT INTO client_user_right(userID,rightID)VALUES(1,34)");
   string sqlh=string.Format("INSERT INTO client_user_right(userID,rightID)VALUES(1,35)");
   string sqli=string.Format("INSERT INTO client_user_right(userID,rightID)VALUES(1,36)");
   string sqlj=string.Format("INSERT INTO client_user_right(userID,rightID)VALUES(1,37)");
   al.AddRange(new string[]{sqla,sqlb,sqlc,sqld,sqle,sqlf,sqlg,sqlh,sqli,sqlj});

//   string s1   =string.Format("SELECT COUNT(*) FROM model_infor WHERE ModelID='G0109' AND ModelVersion='1110'");
//   string s2   =string.Format("SELECT COUNT(*) FROM model_infor WHERE ModelID='G1103' AND ModelVersion='1110'");
//   string s3   =string.Format("SELECT COUNT(*) FROM model_infor WHERE ModelID='G1402' AND ModelVersion='1110'");
//   string s4   =string.Format("SELECT COUNT(*) FROM model_infor WHERE ModelID='G1403' AND ModelVersion='1110'");
//   string s5   =string.Format("SELECT COUNT(*) FROM model_infor WHERE ModelID='G1401' AND ModelVersion='1110'");
//   string s6   =string.Format("SELECT COUNT(*) FROM model_infor WHERE ModelID='GF1401' AND ModelVersion='1110'");
//   string s7   =string.Format("SELECT COUNT(*) FROM model_infor WHERE ModelID='GF1403' AND ModelVersion='1110'");
//   string s8   =string.Format("SELECT COUNT(*) FROM model_infor WHERE ModelID='S3j00' AND ModelVersion='1110'");
//   string s9   =string.Format("SELECT COUNT(*) FROM model_infor WHERE ModelID='S4200' AND ModelVersion='1110'");
//   string s0   =string.Format("SELECT COUNT(*) FROM model_infor WHERE ModelID='S4700' AND ModelVersion='1110'");
//   if(DB_Class_OneRecord(s1)=="0")
//    al.Add(sql1);
//   if(DB_Class_OneRecord(s2)=="0")
//    al.Add(sql2);
//   if(DB_Class_OneRecord(s3)=="0")
//    al.Add(sql3);
//   if(DB_Class_OneRecord(s4)=="0")
//    al.Add(sql4);
//   if(DB_Class_OneRecord(s5)=="0")
//    al.Add(sql5);
//   if(DB_Class_OneRecord(s6)=="0")
//    al.Add(sql6);
//   if(DB_Class_OneRecord(s7)=="0")
//    al.Add(sql7);
//   if(DB_Class_OneRecord(s8)=="0")
//    al.Add(sql8);
//   if(DB_Class_OneRecord(s9)=="0")
//    al.Add(sql9);
//   if(DB_Class_OneRecord(s0)=="0")
//    al.Add(sql0);
   #endregion
   string usql=string.Format("update clientdb.fitech_version set ver='V5.0' where id =1");
       al.Add(usql);
//   string filePath=rootPath+"\\model_infor.txt";
//   string lsql =string.Format("LOAD DATA INFILE '{0}' REPLACE INTO TABLE model_infor FIELDS TERMINATED BY ',' ESCAPED BY ''",filePath);
//       al.Add(lsql);
   string disql=string.Format("delete from report_infor where EF_Version='1110'");
   al.Add(disql);
   string dsql =string.Format("INSERT INTO report_infor(EF_ExcelName,EF_ModelID,EF_Version)SELECT IF(MainTitle=SubTitle,MainTitle,CONCAT(MainTitle,SubTitle)) AS NewName,ModelID,ModelVersion FROM model_infor m WHERE m.ModelVersion='1110'");
       al.Add(dsql);
   if(al.Count==0)
    return true;
   string []sql=(string[])al.ToArray(typeof(string));
   return DB_Class_ExecuteSqlByTransaction(sql);  
  }
  /// <summary>
  /// 启动MySQL
  /// </summary>
  /// <returns>true or false</returns>
  private bool StartMysql()
  {  
   bool isTrue    =false;
   //MySQL服务是否存在
   bool mysqlExist=false;
   System.ServiceProcess.ServiceController[] mysera= System.ServiceProcess.ServiceController.GetServices();
   for(int i=0;i<mysera.Length;i++)
   { 
    if(mysera[i].ServiceName.ToUpper().Length>=5)
    {  
     #region
     if(mysera[i].ServiceName.ToUpper().Substring(0,5).Equals("MYSQL"))
     {  
      mysqlExist=true;
      if(mysera[i].Status==System.ServiceProcess.ServiceControllerStatus.Running)
      {
       isTrue=true;
       break;
      }
      else
      { 
       try
       {
        if(StartSQL())
         isTrue=true;
        else
                                    isTrue=false;
        break;
       }
       catch
       {
        isTrue=false;
        break;
       }
      }
     }
     #endregion     
    }
   }
   progressBar1.Value++;
   //当MySQL不存在
   if(!mysqlExist)
   {
    if(!RegMySQL())
    {
       MessageBox.Show("注册MySQL服务失败","提示",MessageBoxButtons.OK,MessageBoxIcon.Information);
       isTrue    =false;
    }
    if(!StartSQL())
    {
       MessageBox.Show("启动MySQL服务失败","提示",MessageBoxButtons.OK,MessageBoxIcon.Information);
       isTrue    =false;
    }
    isTrue    =true;   
   }
   progressBar1.Value++;
   return isTrue;
  }
  /// <summary>
  /// 注册MySQL服务
  /// </summary>
  /// <returns>true or false</returns>
  private bool RegMySQL()
  {  
   string path = this.textBox1.Text;   
   string baseDir  = path+"\\mysql";   
   string dataDir   = baseDir+"\\data";
   string serverDir = baseDir+"\\bin\\mysqld-nt.exe";
   WriteMyIni(baseDir.Replace('\\', '/'), dataDir.Replace('\\', '/'), serverDir.Replace('\\', '/'));           
   string cmd = string.Format("sc create MySQL binpath= {0}  type= own start= auto", serverDir);
   if (!CMDLine(cmd))
    return false;
   return true;
  }
  /// <summary>
  /// 向C:\\Windows写入my.ini MySQL配置文件
  /// </summary>
  /// <param name="baseDir">基本目录</param>
  /// <param name="dataDir">数据目录</param>
  /// <param name="serverDir">服务目录</param>
  private void WriteMyIni(string baseDir,string dataDir,string serverDir)
  {
   //2006-1-26(ty)
   //将mysql的my.ini放在c:\\
   const int nChars = 128;
   StringBuilder Buff = new StringBuilder(nChars);
   GetWindowsDirectory(Buff, nChars);
   string windowsPath = Buff.ToString() + "\\my.ini";
   //写my.ini
   string pa = Environment.CurrentDirectory;

   string basedir, datadir, server;
   //   string stname;
   string myini = "[mysqld]\r\n";
   myini += "default-character-set=gb2312\r\n";
   myini += "port=3306\r\n";
   myini += "# set basedir to your installation path\r\n";
   myini += "basedir=" + baseDir + "\r\n";
   myini += "# set datadir to the location of your data directory\r\n";
   myini += "datadir=" + dataDir + "\r\n";
   myini += "[WinMySQLAdmin]\r\n";
   myini += "Server=" + serverDir + "\r\n";
   myini += "default-character-set=gb2312\r\n";
   myini += "default-storage-engine=INNODB\r\n";
   myini += "sql-mode=\"STRICT_TRANS_TABLES,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION\"\r\n";
   myini += "max_connections=100\r\n";
   myini += "query_cache_size=0\r\n";
   myini += "table_cache=256\r\n";
   myini += "tmp_table_size=5M\r\n";
   myini += "thread_cache_size=8\r\n";
   myini += "myisam_max_sort_file_size=100G\r\n";
   myini += "myisam_max_extra_sort_file_size=100G\r\n";
   myini += "myisam_sort_buffer_size=8M\r\n";
   myini += "key_buffer_size=8M\r\n";
   myini += "read_buffer_size=64K\r\n";
   myini += "read_rnd_buffer_size=256K\r\n";
   myini += "sort_buffer_size=212K\r\n";
   myini += "innodb_additional_mem_pool_size=2M\r\n";
   myini += "innodb_flush_log_at_trx_commit=1\r\n";
   myini += "innodb_log_buffer_size=1M\r\n";
   myini += "innodb_buffer_pool_size=8M\r\n";
   myini += "innodb_log_file_size=10M\r\n";
   myini += "innodb_thread_concurrency=8\r\n";
   myini += "[client]\r\n";
   myini += "default-character-set=gb2312\r\n";
   if (System.IO.File.Exists(windowsPath))
   {
    System.IO.File.Delete(windowsPath);
   }
   WriteFile(myini, windowsPath);

  }
  /// <summary>
  /// 向文件中写入内容
  /// </summary>
  /// <param name="content">内容</param>
  /// <param name="fileName">文件名称</param>
  private void WriteFile(string content, string fileName)
  {
   FileStream fs;
   StreamWriter writer;
   try
   {
    fs = new FileStream(fileName, FileMode.Create, FileAccess.Write);
    writer = new StreamWriter(fs);
    writer.Flush();
    writer.BaseStream.Seek(0, SeekOrigin.Begin);
    writer.Write(content);
    writer.Flush();
    writer.Close();
    fs.Close();
   }
   catch (Exception ex)
   {
    string aa = ex.Message;
   }
   finally
   {

   }
  }
  /// <summary>
  /// 启动MySQL
  /// </summary>
  /// <returns>true or false</returns>
  private bool StartSQL()
  {  
   System.Diagnostics.Process Proc2=new Process();
   Proc2.StartInfo.FileName="cmd.exe";   
   Proc2.StartInfo.UseShellExecute = false;
   Proc2.StartInfo.RedirectStandardInput = false;
   Proc2.StartInfo.RedirectStandardOutput = false;
   Proc2.StartInfo.RedirectStandardError = true;
   Proc2.StartInfo.CreateNoWindow = false;     
   Proc2=System.Diagnostics.Process.Start("CMD.exe","/c net start mysql"); 
   
   Proc2.WaitForExit(5000);
   if(!Proc2.HasExited)
   {
    Proc2.WaitForExit(3000);
   }
   Proc2.Close();
   return true;
  }
  /// <summary>
  /// 停止MySQL
  /// </summary>
  /// <returns>true or false</returns>
  private bool StopSQL()
  {  
   System.Diagnostics.Process Proc2=new Process();
   Proc2.StartInfo.FileName="cmd.exe";
   Proc2.StartInfo.UseShellExecute = false;
   Proc2.StartInfo.RedirectStandardInput = false;
   Proc2.StartInfo.RedirectStandardOutput = false;
   Proc2.StartInfo.RedirectStandardError = true;
   Proc2.StartInfo.CreateNoWindow = false;     
   Proc2=System.Diagnostics.Process.Start("CMD.exe","/c net stop mysql");
    
   Proc2.WaitForExit(5000);
   if(!Proc2.HasExited)
   {
    Proc2.WaitForExit(3000);
   }
   Proc2.Close();
   return true;
  }
  /// <summary>
  /// 命令行程序
  /// </summary>
  /// <param name="cmd">cmd命令行</param>
  /// <returns>true or false</returns>
  private bool CMDLine(string cmd)
  {  
   try
   {
    System.Diagnostics.Process Proc2=new Process();
    Proc2.StartInfo.FileName="cmd.exe";
    Proc2.StartInfo.UseShellExecute = false;
    Proc2.StartInfo.RedirectStandardInput = false;
    Proc2.StartInfo.RedirectStandardOutput = false;
    Proc2.StartInfo.RedirectStandardError = true;
    Proc2.StartInfo.CreateNoWindow = false;     
    Proc2=System.Diagnostics.Process.Start("CMD.exe",string.Format("/c {0}",cmd));
    
    Proc2.WaitForExit(5000);
    if(!Proc2.HasExited)
    {
     Proc2.WaitForExit(3000);
    }
    Proc2.Close();
    return true;
   }
   catch(Exception ex)
   {
      MessageBox.Show(ex.Message);
      MessageBox.Show(ex.Source);
      MessageBox.Show(ex.ToString());
      return false;
   }
   
  }
  /// <summary>
  /// 停止MySQL
  /// </summary>
  /// <returns>true or false</returns>
  private bool StopMysql()
  {  
   bool isTrue=false;
   System.ServiceProcess.ServiceController[] mysera= System.ServiceProcess.ServiceController.GetServices();
   for(int i=0;i<mysera.Length;i++)
   { 
    if(mysera[i].ServiceName.ToUpper().Length>=5)
    {
     if(mysera[i].ServiceName.ToUpper().Substring(0,5).Equals("MYSQL"))
     {  
      if(mysera[i].Status==System.ServiceProcess.ServiceControllerStatus.Stopped)
      {
        isTrue=true;
           break;
      }
      if(mysera[i].Status==System.ServiceProcess.ServiceControllerStatus.Running)
      {
       try
       {
        if(StopSQL())
          isTrue=true;
        else
                                  isTrue=false;
        break;
       }
       catch
       {
        isTrue=false;
        break;
       }
      }      
     }
    }
   }
   return isTrue;
  }
  /// <summary>
  /// 获得连接字符串
  /// </summary>
  /// <returns>字符串</returns>
  private string GetConString()
  {
   return string.Format("server=localhost;database=clientdb;user id=root; pwd=;");
  }
  /// <summary>
  /// 使用事务执行一组sql语句,一般为insert,update,delete开头的语句。
  /// </summary>
  /// <param name="sql">需要执行的sql语句</param>
  private  bool DB_Class_ExecuteSqlByTransaction(string[] sql)
  {
   int n = 0;
   bool issucc = false;
   MySqlConnection mycon=new MySqlConnection(GetConString());
   if (mycon.State == ConnectionState.Closed)
   {
    try
    {
     mycon.Open();
    }
    catch
    {
       MessageBox.Show("打开数据库连接失败,请重新尝试","提示",MessageBoxButtons.OK,MessageBoxIcon.Information);
       return false;
    }
   }
   MySqlTransaction _cusTrans = mycon.BeginTransaction();           
   try
   {
    MySqlCommand mycom = new MySqlCommand();
    mycom.Connection = mycon;
    mycom.Transaction = _cusTrans;
    if (sql.Length > 0)
    {
     int i;
     for (i = 0; i < sql.Length; i++)
     {
      if (sql[i] == string.Empty)
      {
       n++;
       continue;
      }
      mycom.CommandText = sql[i];
      n=n+mycom.ExecuteNonQuery();
     }
     _cusTrans.Commit();
     issucc = true;
    }               
   }
   catch(Exception ex)
   {
    _cusTrans.Rollback();               
   }
   finally
   {
    mycon.Close();
   }
   return issucc;
  }
  /// <summary>
  /// 返回一条记录
  /// </summary>
  /// <param name="sql">SQL语句</param>
  /// <returns>DataReader 接口</returns>
  private  string DB_Class_OneRecord(string sql)
  {
   string relValue ="0";
   MySqlConnection mycon=new MySqlConnection(GetConString());
   if (mycon.State == ConnectionState.Closed)
   {  
    try
    { 
     mycon.Open();
    }
    catch(Exception ex)
    {  
     MessageBox.Show(ex.Message);
     MessageBox.Show("打开数据库连接失败,请重新尝试","提示",MessageBoxButtons.OK,MessageBoxIcon.Information);
     return "0";
    }
   }
   MySqlCommand mycom = new MySqlCommand(sql, mycon);
   IDataReader dr = mycom.ExecuteReader();
   try
   {  
    while (dr.Read())
    {
     relValue=dr[0].ToString();
     break;
    }               
   }
   catch
   {
   }
   finally
   {  
    if(!dr.IsClosed)
     dr.Close();
    mycon.Close();
   }
   return relValue;
  }

  /// <summary>
  /// 加解密数据升级文件
  /// </summary>
  /// <param name="oleFileName">旧文件</param>
  /// <param name="newFileName">新文件</param>
  /// <returns>true or false</returns>
  private bool addkeyWord(string oleFileName, string newFileName)
  {  
   try
   {
    FileStream fs = new FileStream(oleFileName, FileMode.Open);
    int length = (int)fs.Length;
    byte[] buffer = new byte[length];
    fs.Read(buffer, 0, length);
    fs.Close();
    byte[] buffer2 = new byte[length];
    int m = length;
    for (int i = 0; i < length; i++)
    {
     buffer2[i] = buffer[m - 1];
     m--;
    }
    FileStream swt = new FileStream(newFileName, FileMode.Create);
    swt.Write(buffer2, 0, length);
    swt.Close();
   }
   catch
   {
    return false;
   }
   return true;
  }
  /// <summary>
  /// 解压文件
  /// </summary>
  /// <param name="args">文件路径</param>
  /// <returns>true or false</returns>
  private bool UnZip(string[] args)
  {  
   try
   {  
    ZipInputStream s = new ZipInputStream(System.IO.File.OpenRead(args[0]));
    string directoryName = System.IO.Path.GetDirectoryName(args[1]);
    
    //生成解压目录
    Directory.CreateDirectory(directoryName);
    ZipEntry theEntry;
    while ((theEntry = s.GetNextEntry()) != null) 
    {     
     
     string fileName      = Path.GetFileName(theEntry.Name);
     if (fileName != String.Empty) 
     {   
      //解压文件到指定的目录
      FileStream streamWriter = System.IO.File.Create(args[1]+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();
   }
   catch
   {
      return false;
   }
     return true;
    }
  
  
  }
 }

 

posted on 2011-01-13 10:58  sky@fly  阅读(714)  评论(1)    收藏  举报