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
}
}