天天看點

c#寫的sql Server資料庫自動備份程式

這幾天寫了一個xp下安裝sql Server 2005 express版本的資料庫自動備份程式,大家看看若是有覺得不合理的地方歡迎指正

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Xml;
using Microsoft.Win32;
using System.Diagnostics;


namespace CPU卡表資料庫備份程式
{
    public partial class Config : Form
    {
        public Config()
        {
            InitializeComponent();
        }


        private void Config_Load(object sender, EventArgs e)
        {
            //this.Cb_Hour.SelectedIndex = 0;
            //this.Cb_Minute.SelectedIndex = 0;
            string Dir_Source = GetValue("Dir");
            this.Txt_DirSource.Text = Dir_Source;
            string Hour = GetValue("Hour").Trim();
            string Minute = GetValue("Minute").Trim();
            this.Cb_Hour.Text = Hour;
            this.Cb_Minute.Text = Minute;
            string AutoRun = GetValue("AutoRun");
            if (AutoRun.Trim() == "false")
            {
                this.CheckBox_AutoRun.Checked = false;
            }
            else
            {
                this.CheckBox_AutoRun.Checked = true;
            }
        }


        private void Txt_DirSource_MouseClick(object sender, MouseEventArgs e)
        {
            FolderBrowserDialog dialog = new FolderBrowserDialog();
            dialog.Description = "請選擇備份路徑";
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                this.Txt_DirSource.Text = dialog.SelectedPath;
            }
            else
            {
                return;
            }
        }


        private void Btn_SetDir_Click(object sender, EventArgs e)
        {
            //首先判斷目錄是否存在
            string Dir_Source = this.Txt_DirSource.Text.Trim();
            if (Dir_Source == "" || Directory.Exists(Dir_Source) == false)
            {
                MessageBox.Show("備份目錄設定有誤,請查證", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            else
            {
                SetValue("Dir", Dir_Source);
                MessageBox.Show("備份目錄設定為"+Dir_Source,"提示",MessageBoxButtons.OK,MessageBoxIcon.Information);
                return;
 
            }
            
        }
        /// <summary>
        /// 設定程式開機啟動
        /// 或取消開機啟動
        /// </summary>
        /// <param name="started">設定開機啟動,或者取消開機啟動</param>
        /// <param name="exeName">系統資料庫中程式的名字</param>
        /// <param name="path">開機啟動的程式路徑</param>
        /// <returns>開啟或則停用是否成功</returns>
        public static bool runWhenStart(bool started, string exeName, string path)
        {
            RegistryKey key = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);//打開系統資料庫子項
            if (key == null)//如果該項不存在的話,則建立該子項
            {
                key = Registry.LocalMachine.CreateSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run");
            }
            if (started == true)
            {
                try
                {
                    key.SetValue(exeName, path);//設定為開機啟動
                    key.Close();
                }
                catch
                {
                    return false;
                }
            }
            else
            {
                try
                {
                    key.DeleteValue(exeName);//取消開機啟動
                    key.Close();
                }
                catch
                {
                    return false;
                }
            }
            return true;
        }
        public string GetValue(string AppKey)
        {
            XmlDocument xDoc = new XmlDocument();
            //擷取可執行檔案的路徑和名稱 
            //MessageBox.Show(Application.StartupPath);
            xDoc.Load(System.Windows.Forms.Application.StartupPath + "/" + "Config.xml");
            XmlNode xNode;
            XmlElement xElem1;
            xNode = xDoc.SelectSingleNode("Settings");
            xElem1 = (XmlElement)xNode.SelectSingleNode(AppKey);
            if (xElem1 != null)
                return xElem1.InnerText;
            else
                return "";
        }
        public void SetValue(string AppKey, string AppValue)
        {
            XmlDocument xDoc = new XmlDocument();
            //擷取可執行檔案的路徑和名稱 
            xDoc.Load(System.Windows.Forms.Application.StartupPath + "/" + "Config.xml");
            XmlNode xNode;
            XmlElement xElem1;
            XmlElement xElem2;
            xNode = xDoc.SelectSingleNode("Settings");
            xElem1 = (XmlElement)xNode.SelectSingleNode(AppKey);
            if (xElem1 != null)
                xElem1.InnerText = AppValue;
            else
            {
                xElem2 = xDoc.CreateElement(AppKey);
                xElem2.Value = AppValue;
                xNode.AppendChild(xElem2);
            }
            xDoc.Save(Directory.GetCurrentDirectory() + "/" + "Config.xml");
        }


        private void Btn_Time_Config_Click(object sender, EventArgs e)
        {
            if (this.Cb_Hour.Text.Trim()=="")
            {
                MessageBox.Show("小時資料不能為空","提示",MessageBoxButtons.OK,MessageBoxIcon.Information);
                return;
            }
            else if (this.Cb_Minute.Text.Trim() == "")
            {
                MessageBox.Show("分鐘資料不能為空", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            else
            {
                SetValue("Hour",this.Cb_Hour.Text.Trim());
                SetValue("Minute",this.Cb_Minute.Text.Trim());
                MessageBox.Show("備份時間配置成功","提示",MessageBoxButtons.OK,MessageBoxIcon.Information);
                return;
            }
        }


        private void Btn_AutoRun_Click(object sender, EventArgs e)
        {
            if (this.CheckBox_AutoRun.Checked == true)
            {
                //首先修改文檔
                SetValue("AutoRun", "true");
                //然後設定修改值
                if (runWhenStart(true, "AutoBackupDatabase", Directory.GetCurrentDirectory() + "/" + "CPU卡表資料庫備份程式.exe") == true)
                {
                    MessageBox.Show("備份程式設定為開機啟動", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
                else
                {
                    MessageBox.Show("程式設定開機啟動過程中發生未知錯誤請查證","提示",MessageBoxButtons.OK,MessageBoxIcon.Warning);
                    return;
 
                }
            }
            else
            {
                SetValue("AutoRun","false");
                if (runWhenStart(true, "AutoBackupDatabase", Directory.GetCurrentDirectory() + "/" + "CPU卡表資料庫備份程式.exe") == true)
                {
                    MessageBox.Show("備份程式取消開機啟動", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
                else
                {
                    MessageBox.Show("程式取消開機啟動過程中發生未知錯誤請查證", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;


                }
            }
        }


        private void button1_Click(object sender, EventArgs e)
        {
            string str5 = Application.StartupPath;
        }
    }
}
           
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.Data.SqlClient;
using SQLDMO;
using System.IO;


namespace CPU卡表資料庫備份程式
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        int Hour;
        int Minute;
        private void 關于我們ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            AboutUs au = new AboutUs();
            au.Show();
        }


        private void Form1_Load(object sender, EventArgs e)
        {
            string DatabaseName = GetValue("DatabaseName");
            this.Txt_Database_Name.Text = DatabaseName;
            Hour = int.Parse(GetValue("Hour"));
            Minute = int.Parse(GetValue("Minute"));
            string Dir = GetValue("Dir");
            this.Txt_Dir.Text = Dir;






        }
        public string GetValue(string AppKey)
        {
            XmlDocument xDoc = new XmlDocument();
            //擷取可執行檔案的路徑和名稱
            //2012年7月20日修改程式
            //MessageBox.Show(System.Windows.Forms.Application.StartupPath);
            xDoc.Load(System.Windows.Forms.Application.StartupPath + "/" + "Config.xml");
            XmlNode xNode;
            XmlElement xElem1;
            xNode = xDoc.SelectSingleNode("Settings");
            xElem1 = (XmlElement)xNode.SelectSingleNode(AppKey);
            if (xElem1 != null)
                return xElem1.InnerText;
            else
                return "";
        }
        public void SetValue(string AppKey, string AppValue)
        {
            XmlDocument xDoc = new XmlDocument();
            //擷取可執行檔案的路徑和名稱 
            xDoc.Load(System.Windows.Forms.Application.StartupPath + "/" + "Config.xml");
            XmlNode xNode;
            XmlElement xElem1;
            XmlElement xElem2;
            xNode = xDoc.SelectSingleNode("Settings");
            xElem1 = (XmlElement)xNode.SelectSingleNode(AppKey);
            if (xElem1 != null)
                xElem1.InnerText = AppValue;
            else
            {
                xElem2 = xDoc.CreateElement(AppKey);
                xElem2.Value = AppValue;
                xNode.AppendChild(xElem2);
            }
            xDoc.Save(Directory.GetCurrentDirectory() + "/" + "Config.xml");
        }


        private void Btn_Save_Click(object sender, EventArgs e)
        {
            SetValue("DatabaseName",this.Txt_Database_Name.Text.Trim());
            MessageBox.Show("配置成功","提示",MessageBoxButtons.OK,MessageBoxIcon.Information);
            return;
        }


        private void Btn_Dir_Click(object sender, EventArgs e)
        {
            //2012年7月19日修改程式源代碼增加記錄功能使用者選擇路徑之後自動儲存路徑友善下次使用
            FolderBrowserDialog dialog = new FolderBrowserDialog();
            dialog.Description = "請選擇備份路徑";
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                this.Txt_Dir.Text = dialog.SelectedPath;
            }
            else
            {
                return;
            }
        }
        private SQLDMO.Backup backup;
        private void Btn_Backup_Click(object sender, EventArgs e)
        {
            if (this.Txt_Dir.Text.Trim() == "")
            {
                MessageBox.Show("請選擇備份目錄","提示",MessageBoxButtons.OK,MessageBoxIcon.Information);
                return;
            }
            else
            {
                backup = new SQLDMO.Backup();
                SQLDMO.SQLServer sqlServer = new SQLDMO.SQLServer();
                backup.PercentComplete += new BackupSink_PercentCompleteEventHandler(backup_PercentComplete);
                try
                {
                    this.toolStripProgressBar1.Visible = true;
                    this.toolStripProgressBar1.Value = 0;
                    sqlServer.Connect(".", "sa", "sa");
                    backup.Action = SQLDMO.SQLDMO_BACKUP_TYPE.SQLDMOBackup_Database;
                    backup.Database = "cpudata";
                    backup.Files = this.Txt_Dir.Text + "/" + DateTime.Now.ToString("yyyy-MM-dd") + ".bak";
                    backup.BackupSetName = "cpudata";
                    backup.BackupSetDescription = "資料庫備份";
                    backup.Initialize = true;
                    backup.PercentCompleteNotification = 1;
                    this.Cursor = Cursors.AppStarting;
                    backup.SQLBackup(sqlServer);


                    this.Cursor = Cursors.Default;
                    this.toolStripProgressBar1.Value = 100;
                    MessageBox.Show("資料庫備份完畢", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;


                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    //return;
                }
                finally
                {
                    sqlServer.DisConnect();


                }
                backup.PercentComplete += new BackupSink_PercentCompleteEventHandler(backup_PercentComplete);
                backup = null;
            }
        }
        private void backup_PercentComplete(string message,int percent)
        {
            char[] a = new char[] { '0','1','2','3','4','5','6','7','8','9'};
            int startPos = message.IndexOfAny(a);
            int endPos = message.LastIndexOfAny(a);
            int value = Convert.ToInt32(message.Substring(startPos,endPos-startPos+1));
            this.toolStripProgressBar1.Value = value;
            this.toolStripStatusLabel1.Text = "已完成進度"+this.toolStripProgressBar1.Value.ToString() + "%";
            System.Windows.Forms.Application.DoEvents();
 
        }


        private void 設定ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Config cf = new Config();
            cf.Show();
        }


        private void timer1_Tick(object sender, EventArgs e)
        {
            DateTime dt = DateTime.Now;
            if (dt.Hour==Hour && dt.Minute==Minute && dt.Second==0)
            {
                //開始執行備份
                this.toolStripStatusLabel1.Text = "開始執行資料庫備份程式……";
                backup = new SQLDMO.Backup();
                SQLDMO.SQLServer sqlServer = new SQLDMO.SQLServer();
                backup.PercentComplete += new BackupSink_PercentCompleteEventHandler(backup_PercentComplete);
                try
                {
                    this.toolStripProgressBar1.Visible = true;
                    this.toolStripProgressBar1.Value = 0;
                    sqlServer.Connect(".", "sa", "sa");
                    backup.Action = SQLDMO.SQLDMO_BACKUP_TYPE.SQLDMOBackup_Database;
                    backup.Database = "cpudata";
                    backup.Files = this.Txt_Dir.Text + "/" + DateTime.Now.ToString("yyyy-MM-dd") + ".bak";
                    backup.BackupSetName = "cpudata";
                    backup.BackupSetDescription = "資料庫備份";
                    backup.Initialize = true;
                    backup.PercentCompleteNotification = 1;
                    this.Cursor = Cursors.AppStarting;
                    backup.SQLBackup(sqlServer);


                    this.Cursor = Cursors.Default;
                    this.toolStripProgressBar1.Value = 100;
                    MessageBox.Show("資料庫備份完畢", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;


                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    //return;
                }
                finally
                {
                    sqlServer.DisConnect();


                }
                backup.PercentComplete += new BackupSink_PercentCompleteEventHandler(backup_PercentComplete);
                backup = null;
                this.toolStripStatusLabel1.Text = "勝利油田恒達電氣";
            }
        }


        private void 關閉ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }


        private void 還原ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.WindowState = FormWindowState.Normal;
            this.ShowInTaskbar = true;
        }


        private void Form1_SizeChanged(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Minimized)
            {
                this.WindowState = FormWindowState.Minimized;
                this.ShowInTaskbar = false;
            } 
        }


        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            this.notifyIcon1.Visible = false;
        }


        private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            this.WindowState = FormWindowState.Normal;
            this.ShowInTaskbar = true;


        }
    }
}