using System.Configuration; using System.Data; using System.IO.Compression; using System.IO; using System.Security.Cryptography; using System.Text; using System.Windows; namespace ArchivesCenter3 { /// /// Interaction logic for App.xaml /// public partial class App : Application { protected override void OnStartup(StartupEventArgs e) { base.OnStartup(e); this.SessionEnding += App_SessionEnding; } private void App_SessionEnding(object sender, SessionEndingCancelEventArgs e) { try { // 获取用户文档库路径 string documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); string archivesCenterPath = Path.Combine(documentsPath, "ArchivesCenter"); string dataPath = Path.Combine(archivesCenterPath, "data"); string configPath = Path.Combine(archivesCenterPath, "config"); string backupPath = Path.Combine(archivesCenterPath, "backup"); // 确保备份文件夹存在 Directory.CreateDirectory(backupPath); // 获取当前时间作为文件名 string timestamp = DateTime.Now.ToString("yyyyMMddHHmmssfff"); string backupFileName = Path.Combine(backupPath, $"backup_{timestamp}.zip"); // 获取加密密码 string password = Settings1.Default.Password; // 创建压缩包并加密 using (FileStream zipToOpen = new FileStream(backupFileName, FileMode.Create)) { using (ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Create, true)) { // 添加 data 文件夹 if (Directory.Exists(dataPath)) { AddDirectoryToArchive(archive, dataPath, "data"); } // 添加 config 文件夹 if (Directory.Exists(configPath)) { AddDirectoryToArchive(archive, configPath, "config"); } } } // 加密压缩包 EncryptFile(backupFileName, backupFileName + ".enc", password); // 删除未加密的压缩包 File.Delete(backupFileName); MessageBox.Show("备份完成,文件已加密并保存到:\n" + backupFileName + ".enc"); } catch (Exception ex) { MessageBox.Show("备份失败:" + ex.Message); } } private void AddDirectoryToArchive(ZipArchive archive, string directoryPath, string entryName) { foreach (string file in Directory.GetFiles(directoryPath, "*.*", SearchOption.AllDirectories)) { string entryFilePath = Path.GetRelativePath(directoryPath, file); ZipArchiveEntry entry = archive.CreateEntry(Path.Combine(entryName, entryFilePath)); using (FileStream fileStream = new FileStream(file, FileMode.Open, FileAccess.Read)) { using (Stream entryStream = entry.Open()) { fileStream.CopyTo(entryStream); } } } } private void EncryptFile(string inputFilePath, string outputFilePath, string password) { byte[] passwordBytes = Encoding.UTF8.GetBytes(password); using (Aes aesAlg = Aes.Create()) { aesAlg.Key = passwordBytes; aesAlg.IV = new byte[16]; // IV 长度必须为 16 字节 using (FileStream inputStream = new FileStream(inputFilePath, FileMode.Open, FileAccess.Read)) { using (FileStream outputStream = new FileStream(outputFilePath, FileMode.Create, FileAccess.Write)) { using (ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV)) { using (CryptoStream cryptoStream = new CryptoStream(outputStream, encryptor, CryptoStreamMode.Write)) { inputStream.CopyTo(cryptoStream); } } } } } } } }