首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C# 開發批量 Access 資料庫壓縮工具:核心技術與實作細節

     編輯:關於C語言

專案背景

Access (`.mdb`/`.accdb`) 長期運行後會產生碎片,檔案膨脹、效能下降。定期壓縮修復 (`CompactDatabase`) 是維護常態。本文記錄一套 WinForms 批量壓縮工具的開發過程,涵蓋目錄選擇、檔案掃描、壓縮執行、UI 回報等完整流程,展示 .NET Framework 核心類別的實戰組合。

核心功能模組

1. 目錄選擇:FolderBrowserDialog

兩處使用:選擇「資料庫根目錄」(隱藏新建資料夾按鈕)與「備份目錄」(保留新建按鈕)。

// 選擇資料庫根目錄
var dlg = new FolderBrowserDialog
{
    Description = "選擇所有資料庫檔案所在根目錄",
    ShowNewFolderButton = false, // 隱藏新建
    SelectedPath = string.IsNullOrEmpty(txtDbRoot.Text) ? 
        Environment.GetFolderPath(Environment.SpecialFolder.MyComputer) : 
        txtDbRoot.Text
};

if (dlg.ShowDialog() == DialogResult.OK)
{
    txtDbRoot.Text = dlg.SelectedPath;
    Cls_dbRootPath = dlg.SelectedPath;
}

2. 訊息回饋:MessageBox

  • 一般提示:MessageBox.Show("內容", "標題", MessageBoxButtons.OK, MessageBoxIcon.Information);
  • 雙按鈕確認(備份完成詢問是否開啟目錄):
var result = MessageBox.Show(
    $"資料庫已備份至「{backupPath}」,是否開啟目錄?",
    "備份成功",
    MessageBoxButtons.YesNo,
    MessageBoxIcon.Question);

if (result == DialogResult.Yes)
    OpenDirectory(backupPath);

3. 目錄操作:DirectoryInfo

// 檢查存在
var dir = new DirectoryInfo(path);
if (!dir.Exists) dir.Create(); // 遞迴建立所有層級

// 列舉子目錄/檔案
foreach (var subDir in dir.GetDirectories()) { /* 遞迴處理 */ }
foreach (var file in dir.GetFiles("*.mdb")) { /* 處理 Access 檔 */ }

4. 檔案資訊與操作:FileInfo

var fi = new FileInfo(filePath);
// 取得屬性
long size = fi.Length;
DateTime modified = fi.LastWriteTime;
string name = fi.Name;

// 複製備份(覆寫)
string dest = Path.Combine(backupDir, fi.Name);
if (File.Exists(dest)) File.Delete(dest);
fi.CopyTo(dest);

5. 資料呈現:DataGridView

綁定陣列資料,即時刷新、滾動跟隨、游標定位:

// 新增列
string[] row = { relativePath, formattedSize, "0", "未壓縮", typeName, modified.ToString() };
int rowIndex = dgvFiles.Rows.Add(row);

// 即時滾動到最新列
dgvFiles.FirstDisplayedScrollingRowIndex = rowIndex;
dgvFiles.CurrentCell = dgvFiles.Rows[rowIndex].Cells[0];
dgvFiles.Refresh(); // 強制 UI 更新

6. 刪除選中列:DataRowView

if (dgvFiles.SelectedRows.Count > 0)
{
    var drv = dgvFiles.SelectedRows[0].DataBoundItem as DataRowView;
    drv?.Delete(); // 若綁定 DataTable/DataView 會同步刪除資料源
}

7. 開啟資料夾:Process.Start

private void OpenDirectory(string path)
{
    if (Directory.Exists(path))
        Process.Start("explorer.exe", path);
    else
        MessageBox.Show("目錄不存在", "錯誤", MessageBoxButtons.OK, MessageBoxIcon.Error);
}

壓縮核心邏輯(JRO / DAO / ACE OLEDB)

工具未直接貼出壓縮代碼,但標準做法為:

// 需參考 Microsoft Jet and Replication Objects (JRO) COM 元件
// 或使用 ACE OLEDB Provider
using JRO;

public void CompactAccess(string sourcePath, string destPath)
{
    var jro = new JRO.JetEngine();
    string srcConn = $@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source={sourcePath};Jet OLEDB:Engine Type=5";
    string destConn = $@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source={destPath};Jet OLEDB:Engine Type=5";
    jro.CompactDatabase(srcConn, destConn);
    
    // 完成後以 dest 覆蓋 source(或備份後替換)
}

注意:JRO 僅支援 `.mdb` (Jet 4.0);`.accdb` (ACE) 需使用 `Microsoft.ACE.OLEDB.12.0` Provider 並確保目標機安裝 Access Database Engine。

架構優化建議

  1. 非同步壓縮:耗時操作放入 `BackgroundWorker` 或 `Task.Run`,避免 UI 凍結;透過 `ProgressChanged` 更新 DataGridView。
  2. 錯誤隔離:單一檔案失敗不應中斷整批,記錄錯誤繼續下一個。
  3. 設定持久化:根目錄、備份目錄儲存至 `app.config` 或 `Settings.settings`,下次啟動自動還原。
  4. 日誌記錄:引入 `log4net`/`Serilog` 記錄壓縮前後大小、耗時、錯誤堆疊。
  5. 並行處理:獨立檔案可並行壓縮,`Parallel.ForEach` 配合 `MaxDegreeOfParallelism` 控制併發數。

總結

本工具展示了 WinForms 結合 `FolderBrowserDialog`、`DirectoryInfo`、`FileInfo`、`DataGridView`、`Process` 等 BCL 類別,快速構建實用維護工具的典型模式。核心價值在於「掃描→備份→壓縮→驗證→報表」閉環流程的自動化,大幅降低人工維護成本。現代化重構可考慮遷移至 .NET 6+ / WPF / MAUI,並採用 Dependency Injection、MVVM 模式提升可測試性與擴展性。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved