2009-12-08 33 views

回答

4

你可以尝试这样的

public static void CompactAndRepair(string accessFile, Microsoft.Office.Interop.Access.Application app) 
     { 
      string tempFile = Path.Combine(Path.GetDirectoryName(accessFile), 
           Path.GetRandomFileName() + Path.GetExtension(accessFile)); 

      app.CompactRepair(accessFile, tempFile, false); 
      app.Visible = false; 

      FileInfo temp = new FileInfo(tempFile); 
      temp.CopyTo(accessFile, true); 
      temp.Delete(); 
     } 

看到的东西也Use the CompactRepair method of the Application object to compact and repair the database

+0

我不知道是否增加Microsoft.Office.Interop.Access.Application参考,您的应用程序可能会办公室的特定版本绑定。下面的Code Project解决方案将使用动态绑定来避免这种情况。 – 2014-04-09 00:54:21

1

我曾经在文章:
Compact and Repair an Access Database Programmatically Using C#

我修改了它一下,使其更易于使用:

public static bool CompactAndRepairAccessDB(string source, string destination) 
{ 
    try 
    { 
     JetEngine engine = (JetEngine)HttpContext.Current.Server.CreateObject("JRO.JetEngine"); 
     engine.CompactDatabase(string.Format("Data Source={0};Provider=Microsoft.Jet.OLEDB.4.0;", source), 
      string.Format("Data Source={0};Provider=Microsoft.Jet.OLEDB.4.0;", destination)); 
     File.Copy(destination, source, true); 
     File.Delete(destination); 
     return true; 
    } 
    catch 
    { 
     return false; 
    } 
} 

不要忘记:在Solution Explorer
右键单击参考 - >添加引用 - > COM - >搜索 '喷气机' - >添加“的Microsoft Jet和复制对象......”

,并添加:

using System.IO; 
using JRO;