Access (`.mdb`/`.accdb`) 長期運行後會產生碎片,檔案膨脹、效能下降。定期壓縮修復 (`CompactDatabase`) 是維護常態。本文記錄一套 WinForms 批量壓縮工具的開發過程,涵蓋目錄選擇、檔案掃描、壓縮執行、UI 回報等完整流程,展示 .NET Framework 核心類別的實戰組合。
兩處使用:選擇「資料庫根目錄」(隱藏新建資料夾按鈕)與「備份目錄」(保留新建按鈕)。
// 選擇資料庫根目錄
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;
}
MessageBox.Show("內容", "標題", MessageBoxButtons.OK, MessageBoxIcon.Information);var result = MessageBox.Show(
$"資料庫已備份至「{backupPath}」,是否開啟目錄?",
"備份成功",
MessageBoxButtons.YesNo,
MessageBoxIcon.Question);
if (result == DialogResult.Yes)
OpenDirectory(backupPath);
// 檢查存在
var dir = new DirectoryInfo(path);
if (!dir.Exists) dir.Create(); // 遞迴建立所有層級
// 列舉子目錄/檔案
foreach (var subDir in dir.GetDirectories()) { /* 遞迴處理 */ }
foreach (var file in dir.GetFiles("*.mdb")) { /* 處理 Access 檔 */ }
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);
綁定陣列資料,即時刷新、滾動跟隨、游標定位:
// 新增列
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 更新
if (dgvFiles.SelectedRows.Count > 0)
{
var drv = dgvFiles.SelectedRows[0].DataBoundItem as DataRowView;
drv?.Delete(); // 若綁定 DataTable/DataView 會同步刪除資料源
}
private void OpenDirectory(string path)
{
if (Directory.Exists(path))
Process.Start("explorer.exe", path);
else
MessageBox.Show("目錄不存在", "錯誤", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
工具未直接貼出壓縮代碼,但標準做法為:
// 需參考 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。
本工具展示了 WinForms 結合 `FolderBrowserDialog`、`DirectoryInfo`、`FileInfo`、`DataGridView`、`Process` 等 BCL 類別,快速構建實用維護工具的典型模式。核心價值在於「掃描→備份→壓縮→驗證→報表」閉環流程的自動化,大幅降低人工維護成本。現代化重構可考慮遷移至 .NET 6+ / WPF / MAUI,並採用 Dependency Injection、MVVM 模式提升可測試性與擴展性。