using Microsoft.EntityFrameworkCore; using Serilog; using System; using System.Collections.Generic; using System.Data.SqlClient; using System.IO; using System.Linq; using System.Security.AccessControl; using System.Security.Principal; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Xml.Linq; using WPFWCSDemo.Data; using WPFWCSDemo.StateCode; namespace WPFWCSDemo.Utilities { /// /// 数据维护操作相关 /// public class SqlDatabaseMaintenance { /// /// 手动备份根文件夹路径 /// static string rootPath = @"E:\SqlDataBackup"; /// /// 自动备份根文件夹路径 /// static string rootPathAuto = @"E:\SqlAutoBackup"; /// /// sql库名 /// static string dbName = "FT479"; /// /// 备份当前数据库 /// public static void SQLBackup() { try { // 连接字符串 string connectionString = SqlHelper.ConStr; // 指定备份文件的路径 string backupPath = $@"{rootPath}\{dbName}_{DateTime.Now.ToString("yyyyMMdd_hhmmss")}.bak"; // SQL 查询备份数据库 string backupQuery = $"BACKUP DATABASE {dbName} TO DISK = '{backupPath}' WITH COPY_ONLY, STATS = 10;"; GetOrCreateDirectory(backupPath); // 打开数据库连接 using (SqlConnection connection = new SqlConnection(connectionString)) { connection.Open(); // 执行备份查询 using (SqlCommand command = new SqlCommand(backupQuery, connection)) { command.ExecuteNonQuery(); } MessageBox.Show("数据库备份成功!"); } } catch (Exception ex) { MessageBox.Show($"数据库备份失败: {ex.Message}"); } } /// /// 自动备份当前数据库 /// 包含删除旧数据功能 /// public static void SQLBackupAuto() { try { // 连接字符串 string connectionString = SqlHelper.ConStr; // 指定备份文件的路径 string backupPath = $@"{rootPathAuto}\{DateTime.Now.AddMonths(-4).ToString("yyyy")}\{dbName}_{DateTime.Now.AddMonths(-4).ToString("yyyy-MM")}.bak"; // SQL 查询备份数据库 string backupQuery = $"BACKUP DATABASE {dbName} TO DISK = '{backupPath}' WITH COPY_ONLY, STATS = 10;"; GetOrCreateDirectory(backupPath); Log.Warning("【定期自动备份】自动备份数据中..."); using var context = new AppDbContext(); //备份前删除前3个月外的调度任务记录 context.TaskHistories .Where(t => t.FinishTime < DateTime.Now.AddMonths(-3)) .ExecuteDelete(); //备份前删除前1年前的报警任务记录 context.AlarmHistories .Where(t => t.End_Time < DateTime.Now.AddYears(-1)) .ExecuteDelete(); context.SaveChanges(); // 打开数据库连接 using (SqlConnection connection = new SqlConnection(connectionString)) { connection.Open(); // 执行备份查询 using (SqlCommand command = new SqlCommand(backupQuery, connection)) { command.ExecuteNonQuery(); } } Log.Warning("【定期自动备份】备份完成!"); } catch (Exception ex) { Log.Warning($"【定期自动备份】备份发生错误:{ex.Message}"); } SqlHelper.NewEventLog("系统自动备份操作", "SYSTEM"); } /// /// SQL备份-调度任务表 /// public static void SQLTaskBackup(string yearOrMonthOrDay,int count,bool delete) { try { // 连接字符串 string connectionString = SqlHelper.ConStr; // 指定备份文件的路径 string backupPath = $"{rootPath}\\{dbName}_{DateTime.Now.ToString("yyyyMMdd_hhmmss")}.bak"; // SQL 查询备份数据库 string backupQuery = $"BACKUP DATABASE FT_WCS TO DISK = '{backupPath}' WITH COPY_ONLY, STATS = 10;" + $"SELECT * FROM TASK_HISTORY WHERE CREATETIME >= DATEADD({yearOrMonthOrDay}, {count}, GETDATE())"; GetOrCreateDirectory(backupPath); // 打开数据库连接 using (SqlConnection connection = new SqlConnection(connectionString)) { connection.Open(); // 执行备份查询 using (SqlCommand command = new SqlCommand(backupQuery, connection)) { command.ExecuteNonQuery(); //选择是否删除已备份的数据 if (delete) { SQLClearByTime("TASK_HISTORY", yearOrMonthOrDay, count); } } MessageBox.Show("数据库备份成功!"); Log.Warning($"【手动动备份】备份完成!"); } SqlHelper.NewEventLog("发生了手动备份操作", "USER"); } catch (Exception ex) { MessageBox.Show($"数据库备份失败: {ex.Message}"); Log.Warning($"【手动备份】备份发生错误:{ex.Message}"); } } /// /// SQL备份-历史报警表 /// public static void SQLAlarmBackup(string yearOrMonthOrDay, int count,bool delete) { try { // 连接字符串 string connectionString = SqlHelper.ConStr; // 指定备份文件的路径 string backupPath = $"{rootPath}\\{dbName}_{DateTime.Now.ToString("yyyyMMdd_hhmmss")}.bak"; // SQL 查询备份数据库 string backupQuery = $"BACKUP DATABASE FT_WCS TO DISK = '{backupPath}' WITH COPY_ONLY, STATS = 10;" + $"SELECT * FROM ALARM_LOG WHERE GEN_TIME >= DATEADD({yearOrMonthOrDay}, {count}, GETDATE())"; GetOrCreateDirectory(backupPath); // 打开数据库连接 using (SqlConnection connection = new SqlConnection(connectionString)) { connection.Open(); // 执行备份查询 using (SqlCommand command = new SqlCommand(backupQuery, connection)) { command.ExecuteNonQuery(); //选择是否删除已备份的数据 if (delete) { SQLClearByTime("ALARM_LOG", yearOrMonthOrDay, count); } } MessageBox.Show("数据库备份成功!"); } } catch (Exception ex) { MessageBox.Show($"数据库备份失败: {ex.Message}"); } } /// /// 删除SQL数据 /// public static void SQLClearByTime(string tableName, string yearOrMonthOrDay, int count) { SqlHelper.ExecuteNonQuery($"DELETE FROM {tableName} WHERE GEN_TIME >= DATEADD({yearOrMonthOrDay}, {count}, GETDATE()"); } /// /// 查找文件夹(不存在则创建) /// 查找后为文件夹设定权限-完全控制 /// /// private static void GetOrCreateDirectory(string backupPath) { // 检查备份路径是否存在,如果不存在则创建 if (!Directory.Exists(Path.GetDirectoryName(backupPath))) { Directory.CreateDirectory(Path.GetDirectoryName(backupPath)); try { // 定义文件夹路径 string folderPath = rootPath; // 获取文件夹信息 DirectoryInfo directoryInfo = new DirectoryInfo(folderPath); // 获取当前文件夹的安全性设置 DirectorySecurity directorySecurity = directoryInfo.GetAccessControl(); // 定义 "Authenticated Users" 用户组 NTAccount authenticatedUsers = new NTAccount("Authenticated Users"); // 定义权限(这里使用读取和执行权限) FileSystemRights fileSystemRights = FileSystemRights.FullControl; // 定义授权类型 InheritanceFlags inheritanceFlags = InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit; PropagationFlags propagationFlags = PropagationFlags.None; AccessControlType accessControlType = AccessControlType.Allow; // 创建权限规则 FileSystemAccessRule rule = new FileSystemAccessRule(authenticatedUsers, fileSystemRights, inheritanceFlags, propagationFlags, accessControlType); // 添加权限规则到文件夹的安全性设置 directorySecurity.AddAccessRule(rule); // 设置新的安全性设置到文件夹 directoryInfo.SetAccessControl(directorySecurity); //Console.WriteLine("权限已成功添加到文件夹: " + folderPath); } catch { //Console.WriteLine("添加权限失败: " + ex.Message); } } } } }