首页  编辑  

C# 压缩MDB Access数据库

Tags: /C#/数据库和SQL语句/   Date Created:

C# 中压缩Access数据库的函数

首先到项目当中, 添加引用:
Right Click Reference in the Solution Explorer -> Add Reference -> COM -> search 'jet' -> Add 'Microsoft Jet and Replication Objects...'

然后函数代码如下:
using JRO;

public static bool CompactAndRepairAccessDB(string source)
{
	try
	{
		string tempFile = Path.Combine(Path.GetDirectoryName(source), Path.GetRandomFileName() + Path.GetExtension(source));

		JetEngine engine = (JetEngine)Activator.CreateInstance(Type.GetTypeFromProgID("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;", tempFile));
		File.Delete(source + ".bak");
		File.Move(source, source + ".bak");
		File.Move(tempFile, source);
		return true;
	}
	catch(Exception ex)
	{
		Debug.WriteLine(ex);
		return false;
	}
}