BackupDatabase

本文介绍了一个使用 C# 开发的 SQL Server 数据库备份工具,该工具能够自动停止 SQL Server 服务,备份指定数据库的 MDF 和 LDF 文件,并在备份完成后重新启动服务。此外,还提供了淡入淡出的窗口动画效果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 using System;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.ServiceProcess;
using System.Windows.Forms;
using Microsoft.Win32;

namespace DIYBackupDB
{
    public partial class FormBackupDB : Form
    {
        #region 自定义对象
        private readonly ServiceController dbService;
        private string dbPath;
        #endregion

        #region AnimateWindow
        [DllImport("user32.dll", EntryPoint = "AnimateWindow")]
        private static extern bool AnimateWindow(IntPtr handle, int ms, int flags);
        #endregion

        public FormBackupDB()
        {
            #region
            InitializeComponent();
            dbService = new ServiceController();
            using (RegistryKey sqlKey = Registry.LocalMachine.OpenSubKey(@"Software/Microsoft/MSSQLServer/Setup"))
            {
                dbPath = string.Format(@"{0}/Data", sqlKey.GetValue("SQLPath"));
            }
            var query = from filePath in Directory.GetFiles(dbPath)
                        let FileName = Path.GetFileNameWithoutExtension(filePath)
                        let Extension = Path.GetExtension(filePath).ToLowerInvariant()
                        where Extension == ".mdf" || Extension == ".ldf"
                        group FileName by Extension into Groups
                        orderby Groups.Key ascending
                        select Groups;
            IGrouping<string, string> ldf = query.First(), mdf = query.Last();
            var dsn = from index in Enumerable.Range(0, mdf.Count())
                      let MDF = mdf.ElementAt(index)
                      let LDF = ldf.ElementAt(index)
                      select new { MDF, LDF };
            cmbDatabase.Sorted = false;       // 绑定数据时,禁用排序。
            cmbDatabase.ValueMember = "LDF"; // 绑定数据之前赋值。
            cmbDatabase.DataSource = dsn.ToList();
            cmbDatabase.DisplayMember = "MDF";
            cmbServiceName.DataSource = new string[] { "MSSQLSERVER", "MSSQL$SQLEXPRESS" };
            #endregion
        }

        #region Form_Load
        private void FormBackupDB_Load(object sender, EventArgs e)
        {
            this.TopMost = true;         // 前端显示。
            this.ShowInTaskbar = false; // 在 Windows 任务栏中隐藏窗体。
            this.StartPosition = FormStartPosition.CenterScreen; // 在桌面居中显示。
            this.SizeGripStyle = SizeGripStyle.Hide;            // 隐藏调整大小手柄。
            this.AutoSizeMode = AutoSizeMode.GrowAndShrink;    //  禁用手动调整大小。
            AnimateWindow(this.Handle, 1000, 0xA0000);        // 淡入淡出效果。
        }
        #endregion

        #region BackupDBFile
        private void btnBackupDB_Click(object sender, EventArgs e)
        {
            dbService.Refresh();
            if (dbService.Status != ServiceControllerStatus.Stopped)
                dbService.Stop();
        Wait:
            do
            {
                this.Text = "正在备份数据库中...";
                System.Threading.Thread.Sleep(500);
                dbService.Refresh();
            }
            while (dbService.Status != ServiceControllerStatus.Stopped);
            try
            {
                string fileName = string.Format("{0}.mdf", cmbDatabase.Text);
                File.Copy(Path.Combine(dbPath, fileName), fileName, true);
                fileName = string.Format("{0}.ldf", cmbDatabase.SelectedValue);
                File.Copy(Path.Combine(dbPath, fileName), fileName, true);
                this.Text = "已完成备份数据库!";
            }
            catch (IOException ie)
            {
                ie.Source = null;
                goto Wait;
            }
            catch (Exception se)
            {
                this.Text = null;
                MessageBox.Show(this, se.Message, "系统提示!", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
        #endregion

        #region SetServiceName
        private void cmbServiceName_SelectedIndexChanged(object sender, EventArgs e)
        {
            dbService.ServiceName = cmbServiceName.Text;
            var query = from service in ServiceController.GetServices()
                        let SN = (service.ServiceName == dbService.ServiceName)
                        let ST = (service.ServiceType == ServiceType.Win32OwnProcess)
                        where ST && SN
                        select service;
            btnBackupDB.Enabled = query.Any();
        }
        #endregion

        #region CancelButton
        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void FormBackupDB_FormClosing(object sender, FormClosingEventArgs e)
        {
            AnimateWindow(this.Handle, 1000, 0x90000); // 淡入淡出效果。
            try
            {
                dbService.Refresh();
                if (dbService.Status == ServiceControllerStatus.Stopped)
                    dbService.Start();
            }
            catch
            {
                return;
            }
        }
        #endregion

        #region HelpButton
        private void FormBackupDB_HelpButtonClicked(object sender, System.ComponentModel.CancelEventArgs e)
        {
            e.Cancel = true;
            System.Diagnostics.Process.Start("explorer.exe", Environment.CurrentDirectory).Close();
        }
        #endregion
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值